* generate paper tables and figures
********************************************************************************
* prelims
********************************************************************************
{
clear
set more off
cap log close

* stars for tables
global stars star(* .1 ** .05 *** .01)
global stars2 star
global starsum

cap program drop pStars
program define pStars, sclass
args p_value 

local ps ""
if (`p_value' <= 0.10){
	local ps "*"
}
if (`p_value' <= 0.05){
	local ps "**"
}
if (`p_value' <= 0.01){
	local ps "***"
}

sreturn local pStar "`ps'"

end

}
********************************************************************************
* prepare data
********************************************************************************
{

use "$data/analysis_dataset.dta", clear

* treatment vars
foreach dist in 100 200 350 500 {
forval y = 2019(-1)2014 {
	
	* binary
	g TREAT`dist'_`y' = (Dist1_`y' <= `dist')
	replace TREAT`dist'_`y' = . if CSEC == ""

	* continuos
	g NTREAT`dist'_`y' = 0
	
	forval i = 1(1)5{
		replace NTREAT`dist'_`y' = NTREAT`dist'_`y' + 1 if (Dist`i'_`y' <= `dist')
	}
}

* binary
g T`dist'_2Yrs = (TREAT`dist'_2019==1|TREAT`dist'_2018==1)
g T`dist'_3Yrs = (TREAT`dist'_2019==1|TREAT`dist'_2018==1|TREAT`dist'_2017==1)

* continuos
g NT`dist'_2Yrs = NTREAT`dist'_2019 + NTREAT`dist'_2018
g NT`dist'_3Yrs = NTREAT`dist'_2019 + NTREAT`dist'_2018 + NTREAT`dist'_2017

* times treated
g TimesT`dist' = 0
forval year = 2015(1)2019 {
	replace TimesT`dist' = TimesT`dist' + 1 if TREAT`dist'_`year' == 1

}
}

egen Min_TrDist_1Yrs = rowmin(Dist1_2019)
egen Min_TrDist_2Yrs = rowmin(Dist1_2019 Dist1_2018)
egen Min_TrDist_3Yrs = rowmin(Dist1_2019 Dist1_2018 Dist1_2017)

* labels
la def BldngShock 1 "New Building" 0 "Controls"
la val T350_3Yrs BldngShock

* sample rest
global samplerest if problematic!=1 & NotBCNNET!=1 & NotBCN!=1 & VLNG100!=. 
global AddRest1 & InfoTreatNeigh == 0
global AddRest2 & InfoTreatNeigh == 0 & InfoTreatInc == 0

foreach i in 10 30 50 70 90 99 {
	cap g lnIncp`i' = ln(IncTilesPerc_p`i' + 1)
}

* normalize
g shrforeign_2015 = foreign_2015/pop_2015
g lnMedAptSizeCSEC_2015 = ln(MedAptSizeCSEC_2015)
g lnMedAptSizeCSEC = ln(MedAptSizeCSEC)
g lnMeanAptSizeCSEC = ln(MeanAptSizeCSEC)

* standardize vars
local contSD Age lnIncHH HHNum
#d;
	local tract PopDensity PopDensity_2015 lnMedAptSizeCSEC lnMedAptSizeCSEC_2015 lnMeanAptSizeCSEC
	NAptsCSEC_2015 MedYearConstCSEC_2015 MedYearConstCSEC
	ShrSqmGCCSEC ShrSqmVCSEC ShrSqmGHCSEC ShrSqmGRCSEC ShrSqmOCSEC 
	VLNG200 VLNG350 VLNG500 shrforeign shrforeign_2015 VLNG350_2015 
	ShrSqmVCSEC ShrSqmGCCSEC_2015 ShrSqmGHCSEC_2015 ShrSqmGRCSEC_2015
	MedQualCSECScaled MedQualCSECScaled_2015 PctVotesLEFT_2015
	DistMetro DistPark DistSchool DistHosp
	;
#d cr

#d;
	local outcomes PercGini PrefRedScaled 
	PercIncRank10yrs IncRankPerc Luck
	SLNG100 SLNG200 SLNG350 SLNG500 SLNG750 SLNG1000 
	VLNG100 VLNG200 VLNG350 VLNG500 VLNG750 VLNG1000 
	WVLNG100 WVLNG200 WVLNG350 WVLNG500 WVLNG750 WVLNG1000 
	ChngD3_VLNG100 ChngD3_VLNG200 ChngD3_VLNG350 ChngD3_VLNG500
	ChngD3_SLNG100 ChngD3_SLNG200 ChngD3_SLNG350 ChngD3_SLNG500
	lnIncp10 lnIncp30 lnIncp50 lnIncp70 lnIncp90 lnIncp99
	PrefRed2 lnPerc_ratio9010 lnPerc_ratio9050 PercGiniPyr
	MobilityPoorQ1Q1 MobilityPoorQ1Q5 ImmPercCtry TrustPol
	;
#d cr

foreach var in `contSD' `tract' `outcomes' {

	cap egen `var'SD = std(`var') $samplerest

}

* global for controls
global controlsNoSD Female Married ForeignBorn University Renter Unemployed Religious Left
global contSD AgeSD HHNumSD lnIncHHSD
* tract controls
#d;
global contTract MedQualCSECScaledSD MedYearConstCSECSD shrforeignSD PctVotesLEFT_2015SD DistMetroSD DistParkSD DistSchoolSD DistHospSD
;
#d cr
* tract controls 2015
#d;
global contTract2015 MedQualCSECScaled_2015SD MedYearConstCSEC_2015SD shrforeign_2015SD PctVotesLEFT_2015SD VLNG350_2015SD
	DistMetroSD DistParkSD DistSchoolSD DistHospSD
;
#d cr
* final globals used
global controlsDes $controlsNoSD $contSD $contTract
global controlsQE $controlsNoSD $contSD $contTract2015 

* other globals
g clusvar = BARRI
global fe i.CDISFE
global options cluster(clusvar)

* labels
la def InfoTreatNeigh 1 "Neighborhood Info Treatment"
la val InfoTreatNeigh InfoTreatNeigh
la def InfoTreatInc 1 "Rel Income Info Treatment"
la val InfoTreatInc InfoTreatInc

* variable to replace in regressions
g outcome = .
g LNG = .
la var LNG "LNG"

* checkpoint
save "$data/temp/survanalysis_check_qe.dta", replace

}
********************************************************************************
* Figures 4 & 5 - perceived income distribution and inequality
********************************************************************************
{
preserve

	** FIGURE 5 - Perceived Gini
	****************************************************************************
* load data
use "$data/analysis_dataset.dta", clear	

* sample restriction
keep $samplerest		
	
* fig set up
grstyle init
grstyle set color hue, n(2)
grstyle set imesh, horizontal compact minor
grstyle set legend 6, nobox
grstyle set symbol
grstyle set lpattern

* kernel density
local ActGini = 0.36
local MeanGini = 0.45
local MedGini = 0.42

#d;
	tw (kdensity PercGini, lc(lime*1.5)),
	xtitle("Perceived Gini", size(small)) 
	ytitle("Density", size(small))
	xlabel(0(0.2)1, labsize(small))
	xline(`ActGini', lc(red*0.5) lw(medthin) lp(dash))
	xline(`MedGini', lc("0 200 210") lw(medthin) lp(longdash_dot))
	text(2.5 0.7 "Actual Gini (2018) = `ActGini'", place(se) just(left) size(small))
	text(2.35 0.7 "Median Perceived Gini = `MedGini'", place(se) just(left) size(small))
	ylabel(, labsize(small)) 
	graphregion(color(white)) bgcolor(white)
	;
#d cr
* store
graph export "$figs/PercGini_Density_lines.pdf", replace	

	** FIGURE 4 - Perceived Income Distribution
	****************************************************************************
* load data
use "$data/analysis_dataset.dta", clear	

* sample restriction
keep $samplerest

g AbMed = (IncRankAct >= 0.5)

* adjustment
replace IncRankAct = IncRankAct * 100
replace IncRankPerc = IncRankPerc * 100

grstyle init
grstyle set color hue, n(10)
grstyle set imesh, horizontal compact minor
grstyle set legend 3, nobox
grstyle set symbol
grstyle set lpattern

* need to reshape long
keep RandomID IncTilesPerc_p* University AbMed Left
reshape long IncTilesPerc_p, i(RandomID) j(P)

* replace values between 0 and 1 to 1
replace IncTilesPerc_p = 1 if IncTilesPerc_p<1

* generate log of income
g log10Inc = log10(IncTilesPerc_p)
g logInc = ln(IncTilesPerc_p)

* income over 1000
g log10Inc2 = log10(IncTilesPerc_p/1000)

* marker style
#d;
	local mark marker( symbol(smcircle) linestyle( width(thin) color(black) 
	pattern(solid)) fillcolor(black) size(medsmall) angle(stdarrow) backsymbol(none) 
	backline( width(thin) color(black) pattern(solid)) backcolor(black) 
	backsize(zero) backangle(stdarrow)) line( width(thin) color(black) 
	pattern(solid)) area( linestyle( width(thin) color(white) pattern(solid)) 
	shadestyle( color(white) intensity(inten100) fill(pattern10))) 
	label( textstyle( horizontal(center) vertical(middle) angle(default) size(small) 
	color(black) position() margin(zero) linestyle( width(thin) color(black) pattern(solid))) 
	position(6) textgap(half_tiny) horizontal(default) vertical(default)) dots( symbol(circle) 
	linestyle( width(thin) color(black) pattern(solid)) fillcolor(black) size(vtiny) angle(horizontal) 
	backsymbol(none) backline( width(thin) color(black) pattern(solid)) backcolor(black) backsize(medium) 
	backangle(horizontal)) connect(direct) connect_missings(yes) editcopy	;
#d cr

local ystart = log10(100)
local yend = log10(100000)

* percentiles
local P10 = log10(0.446)
local P30 = log10(0.790)
local P50 = log10(1.144)
local P70 = log10(1.678)
local P90 = log10(2.795)
local P99 = log10(5.791)

mylabels 0.125 0.250 0.500(.5)1 2(2)4 8(8)16 16(16)32 64 128 256, myscale(log10(@)) local(labels)

* box plot
#d;
	graph box log10Inc2 , 
	nooutsides over(P, relabel(1 "P10" 2 "P30" 3 "P50" 4 "P70" 5 "P90" 6 "P99")) box(1, color(lime*1.5))
	ylabel(`labels', angle(h))
	graphregion(color(white)) bgcolor(white)
	;
#d cr

* graph adjustments
gr_edit note.text = {}
gr_edit scaleaxis.title.style.editstyle size(small) editcopy
gr_edit scaleaxis.title.text = {}
gr_edit scaleaxis.title.text.Arrpush Perceived Monthly Income (1000s EUR)
gr_edit scaleaxis.style.editstyle majorstyle(tickstyle(textstyle(size(small)))) editcopy
gr_edit grpaxis.style.editstyle majorstyle(tickstyle(textstyle(size(small)))) editcopy
gr_edit scaleaxis.plotregion.yscale.curmax = 2.5 

gr_edit plotregion1.AddMarker added_markers editor 6.252483920865134 `P10'
gr_edit plotregion1.added_markers_new = 1
gr_edit plotregion1.added_markers_rec = 1
gr_edit plotregion1.added_markers[1].style.editstyle  `mark'

gr_edit plotregion1.AddMarker added_markers editor 23.80635706300613 `P30'
gr_edit plotregion1.added_markers_new = 2
gr_edit plotregion1.added_markers_rec = 2
gr_edit plotregion1.added_markers[2].style.editstyle  `mark'

gr_edit plotregion1.AddMarker added_markers editor 41.30484581466497 `P50'
gr_edit plotregion1.added_markers_new = 3
gr_edit plotregion1.added_markers_rec = 3
gr_edit plotregion1.added_markers[3].style.editstyle  `mark'

gr_edit plotregion1.AddMarker added_markers editor 58.84795017584168 `P70'
gr_edit plotregion1.added_markers_new = 4
gr_edit plotregion1.added_markers_rec = 4
gr_edit plotregion1.added_markers[4].style.editstyle `mark'

gr_edit plotregion1.AddMarker added_markers editor 76.42182331798268 `P90'
gr_edit plotregion1.added_markers_new = 5
gr_edit plotregion1.added_markers_rec = 5
gr_edit plotregion1.added_markers[5].style.editstyle `mark'

gr_edit plotregion1.AddMarker added_markers editor 93.9531206964148 `P99'
gr_edit plotregion1.added_markers_new = 6
gr_edit plotregion1.added_markers_rec = 6
gr_edit plotregion1.added_markers[6].style.editstyle  `mark'

gr_edit plotregion1.AddTextBox added_text editor 2.47 1.101706368704991
gr_edit plotregion1.added_text_new = 1
gr_edit plotregion1.added_text_rec = 1
gr_edit plotregion1.added_text[1].style.editstyle  angle(default) size(small) color(black) horizontal(left) vertical(middle) margin(zero) linegap(zero) drawbox(no) boxmargin(zero) fillcolor(bluishgray) linestyle( width(thin) color(black) pattern(solid)) box_alignment(east) editcopy
gr_edit plotregion1.added_text[1].text = {}
gr_edit plotregion1.added_text[1].text.Arrpush Note: Black markers represent the actual income at the percentile

* store plot
graph export "$figs/Survey_LogIncTiles_lime_marker_Rev.pdf", replace
	
restore

}	
********************************************************************************
* Tables 1 & 5 - LNG on PercGini & PrefRed 
********************************************************************************
{

cap g LNG = .
la var LNG "LNG"

local varstokeep LNG

foreach lng in VLNG {

	foreach outcome in PercGini PrefRedScaled {

	if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
	}
	else if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"	
	}
	
	local tableout LNG mean SD r2 N Controls TractControls FE, fmt(0 3 3 3 0 0 0 0) label("r (meters)" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE")
	
	replace outcome = `outcome'SD

	* clear tables
	eststo clear 
	local varthx 24
	
	foreach dist in 100 200 350 500 750 1000 { 
	
	replace LNG = `lng'`dist'SD
	
* no controls
eststo: reg outcome LNG $fe $samplerest , $options
		format outcome %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		
* yes controls
eststo: reg outcome LNG $controlsDes $fe $samplerest , $options
		format outcome %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
			
		}

* generate table
#d;
esttab using "$tables/Survey_`lng'Dist_`outcome'.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats (`tableout') se	
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} 
} 

}
********************************************************************************
* Table 2 - First Stage
********************************************************************************
{

cap g T350_1Yrs	= TREAT350_2019
cap g TREAT = .
cap g TREATPrev = .
cap g BASE = .

cap la drop TREAT100
cap la drop TREAT200
cap la drop TREAT350
cap la drop TREAT500
cap la drop TREAT

la def TREAT100 1 "New Building (100m)"
la def TREAT200 1 "New Building (200m)"
la def TREAT350 1 "New Building (350m, baseline)"
la def TREAT500 1 "New Building (500m)"
la def TREAT 1 "New Building"
la val TREAT TREAT

la val T100_3Yrs TREAT100
la val T200_3Yrs TREAT200
la val T350_3Yrs TREAT350
la val T500_3Yrs TREAT500

local varstokeep 1.TREAT

	eststo clear 
	local varthx 24
	
foreach lng in VLNG SLNG {
		
		if "`lng'" == "VLNG" {
			local LNGType "Value"
		}
		else if "`lng'" == "SLNG" {
			local LNGType "Space"
		}

foreach dist in 100 200 350 500 {

	foreach yeardist in 3 {
	
		local year = 2019 - `yeardist'
		replace outcome = ChngD`yeardist'_`lng'`dist'SD
		replace TREAT = T`dist'_`yeardist'Yrs

	eststo: reg outcome i.TREAT $fe  $samplerest, $options
		format outcome %9.2f 
		summ ChngD`yeardist'_`lng'`dist' ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local LNG "`LNGType'"
		estadd local Dist "`dist'"
		estadd local Controls ""
		estadd local AddControls ""
		estadd local FE "X"
		estadd local Restr ""
		

	}
} 
} 
		
* generate table
#d;
esttab using "$tables/Survey_QE_FirstStage_VarDist_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats (Dist mean SD r2 N FE, fmt(0 3 3 3 0 0 0) label( "r (meters)" "Dep Var Mean" "Dep Var SD" "R2" "N" "District FE" )) se
		mgroups("$\Delta$ LNG (Value)" "$\Delta$ LNG (Space)", pattern(1 0 0 0 1 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}
********************************************************************************
* Tables 3 & 6 - QE on PercGini & PrefRed
********************************************************************************
{

cap g trlast3 = .
la var trlast3 "New Building"
la val trlast3 BldngShock

local varstokeep 1.trlast3

foreach outcome in PercGini PrefRedScaled {

	* clear tables
	eststo clear 
	local varthx 24
	
	if "`outcome'" == "PercGini" {
		replace trlast3 = T350_3Yrs
		local tit "Perceived Gini"
		local addopts
	}
	else if "`outcome'" == "PrefRedScaled" {
		replace trlast3 = T350_3Yrs
		local tit "Preferences for Redistribution"
		local addopts
	}
	
	local tableout mean SD r2 N Controls TractControls FE DwellYears Renters, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE" "Years in Dwelling" "Sample")
	
	** years rest
	foreach DwellYears in 5 10 15 {
	
	replace outcome = `outcome'SD 	
	
	* no controls
	eststo: reg outcome i.trlast3  $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "Full"
		
	* yes controls
	eststo: reg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "Full"
		
	} 
	
	** renters/owners
	local DwellYears 5
	
	forval renter = 1(-1)0 {
	
		if `renter' == 1 {
			local rentalstat "Renters"
		}
		else if `renter' == 0 {
			local rentalstat "Owners"
		}
	
	replace outcome = `outcome'SD 
	
	* no controls	
	eststo: reg outcome i.trlast3 $fe $samplerest & PropYears >= `DwellYears' & Renter == `renter' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
		
	* yes controls
	eststo: reg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= `DwellYears'  & Renter == `renter', $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
			
	} 
	
* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats ( `tableout') se `addopts'
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} 

}
********************************************************************************
* Table 4 - QE on Perceived Income
********************************************************************************
{

cap g trlast3 = .
la var trlast3 "New Building"
la val trlast3 BldngShock

replace trlast3 = T350_3Yrs 
	
local varstokeep 1.trlast3

	* clear tables
	eststo clear 
	local varthx 24

foreach outcome in lnIncp99 lnIncp90 lnIncp70 lnIncp50 lnIncp30 lnIncp10  {

	local addcontrols 
	local tableout mean SD r2 N Controls TractControls FE , fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE")
	local tit ("Perceived P99" "Perceived P90" "Perceived P70" "Perceived P50" "Perceived P30" "Perceived P10", pattern(1 0 1 0 1 0 1 0 1 0 1 0)
	local addopts 
	local addtabopts erepeat(\cmidrule(lr){@span})
	
	* no controls
	replace outcome = `outcome'SD

eststo: reg outcome i.trlast3 $fe $samplerest & PropYears >= 5  , $options
	summ `outcome' $samplerest & PropYears >= 5  ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local SampleR "Full"

	* controls
	replace outcome = `outcome'SD
	
eststo: reg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= 5  , $options
	summ `outcome' $samplerest & PropYears >= 5 ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local SampleR "Full"
		
} 

* generate table
#d;
esttab using "$tables/Survey_QE_Cont_Inc_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats (`tableout') se `addopts'
		mgroups`tit'
		prefix(\multicolumn{@span}{c}{) suffix(}) span `addtabopts')
;
#d cr
	
}
********************************************************************************
* Figure A2 - ATC price prediction validition
********************************************************************************
{

preserve

use "$data/int/PredPriceForest_ATC.dta", replace

* adjust price
replace PHat = PHat / 1000
replace price = price / 1000

* mean in city
bys year: egen phat_mean = mean(PHat)
bys year: egen p_mean = mean(price)
* mean in district
bys year CDIS: egen p_cdis_med = mean(price)
bys year CDIS: egen phat_cdis_mean = mean(PHat)

* distribution
foreach pct in 10 25 50 75 90 {
	* city
	bys year: egen phat_p`pct' = pctile(PHat), p(`pct')
	bys year: egen p_p`pct' = pctile(price), p(`pct')
	* district
	bys year CDIS: egen phat_cdis_p`pct' = pctile(PHat), p(`pct')
	bys year CDIS: egen p_cdis_p`pct' = pctile(price), p(`pct')

}

* keep one observation per district-year
duplicates drop CDIS year, force

drop BARRI CUSEC price PHat PlotCode

* plot attributes
grstyle init
grstyle set color hue, n(2)
grstyle set imesh, horizontal compact minor
grstyle set legend 3, nobox
grstyle set symbol
grstyle set lpattern

* plot
#d;
	tw (connected phat_p90 year if CDIS==01, lc(blue*1.75) mc(blue*1.75) ms(circle) lp(dash)) 
	(connected p_p90 year if CDIS==01, lc(red) mc(red) ms(circle) lp(line))
	(connected phat_p50 year if CDIS==01, lc(blue*1.75) mc(blue*1.75) ms(diamond) lp(dash)) 
	(connected p_p50 year if CDIS==01, lc(red) mc(red) ms(diamond) lp(line))
	(connected phat_p10 year if CDIS==01, lc(blue*1.75) mc(blue*1.75) ms(triangle) lp(dash)) 
	(connected p_p10 year if CDIS==01, lc(red) mc(red) ms(triangle) lp(line)),
	xlab(2009(2)2019, labsize(small))
	xtit("Year", size(small))
	ylab(, labsize(small) nogrid)
	ytit("Sale Price (1000s EUR)", size(small))
	graphregion(color(white)) bgcolor(white)
	legend(lab(1 "P90 (Prediction)") lab(2 "P90 (ATC)") 
	lab(3 "P50 (Prediction)") lab(4 "P50 (ATC)") 
	lab(5 "P10 (Prediction)") lab(6 "P10 (ATC)") size(vsmall))
	title("Barcelona", size(small))
	saving("$figs/gph/Prediction_ATC_BCN.gph", replace)
	;
#d cr

* by district
grstyle set legend 6, nobox

forval i = 1(1)10 {
	
	if `i' == 1 {
		local tit "Ciutat Vella"
	}
	else if `i' == 2 {
		local tit "Eixample"
	}
	else if `i' == 3 {
		local tit "Sants-Montjuïc"
	}
	else if `i' == 4 {
		local tit "Les Corts"
	}
	else if `i' == 5 {
		local tit "Sarrià-Sant Gervasi"
	}
	else if `i' == 6 {
		local tit "Gràcia"
	}
	else if `i' == 7 {
		local tit "Horta-Guinardó"
	}
	else if `i' == 8 {
		local tit "Nou Barris"
	}
	else if `i' == 9 {
		local tit "Sant Andreu"
	}
	else if `i' == 10 {
		local tit "Sant Martí"
	}
	
#d;
	tw (connected phat_cdis_p90 year if CDIS==`i', lc(blue*1.75) mc(blue*1.75) ms(circle) lp(dash)) 
	(connected p_cdis_p90 year if CDIS==`i', lc(red) mc(red) ms(circle) lp(line))
	(connected phat_cdis_p50 year if CDIS==`i', lc(blue*1.75) mc(blue*1.75) ms(diamond) lp(dash)) 
	(connected p_cdis_p50 year if CDIS==`i', lc(red) mc(red) ms(diamond) lp(line))
	(connected phat_cdis_p10 year if CDIS==`i', lc(blue*1.75) mc(blue*1.75) ms(triangle) lp(dash)) 
	(connected p_cdis_p10 year if CDIS==`i', lc(red) mc(red) ms(triangle) lp(line)),
	xlab(2009(2)2019, labsize(small))
	xtit("Year", size(small))
	ylab(, labsize(small) nogrid)
	ytit("Sale Price (1000s EUR)", size(small))
	graphregion(color(white)) bgcolor(white)
	legend(lab(1 "P90 (Prediction)") lab(2 "P90 (ATC)") 
	lab(3 "P50 (Prediction)") lab(4 "P50 (ATC)") 
	lab(5 "P10 (Prediction)") lab(6 "P10 (ATC)") size(vsmall) rows(1))
	title("`tit'", size(small))
	saving("$figs/gph/Prediction_ATC_CDIS`i'.gph", replace)
	;
#d cr

}

* all districts + barcelona
grstyle set legend 3, nobox

#d;
grc1leg "$figs/gph/Prediction_ATC_BCN.gph" "$figs/gph/Prediction_ATC_CDIS1.gph" "$figs/gph/Prediction_ATC_CDIS2.gph"
"$figs/gph/Prediction_ATC_CDIS3.gph" "$figs/gph/Prediction_ATC_CDIS4.gph"
"$figs/gph/Prediction_ATC_CDIS5.gph" "$figs/gph/Prediction_ATC_CDIS6.gph"
"$figs/gph/Prediction_ATC_CDIS7.gph" "$figs/gph/Prediction_ATC_CDIS8.gph"
"$figs/gph/Prediction_ATC_CDIS9.gph" "$figs/gph/Prediction_ATC_CDIS10.gph",
legendfrom("$figs/gph/Prediction_ATC_BCN.gph")
rows(4) pos(3)
;
#d cr
graph export "$figs/Prediction_ATC_BCN_CDIS.pdf", replace
	
restore
}
********************************************************************************
* Tables A1, A2 & A3 - LNG Correlations
********************************************************************************
{

preserve

* load
use "$data/int/lng_bcn.dta", clear

* data to plot
keep if Year==2019
keep PlotCode *LNG100 *LNG200 *LNG350 *LNG500 *LNG750 *LNG1000

foreach r in 100 200 350 500 750 1000 {
	la var VLNG`r' "LNG`r'"
}

** Table A1
sum VLNG100 VLNG200 VLNG350 VLNG500 VLNG750 VLNG1000

eststo clear
 
estpost sum VLNG100 VLNG200 VLNG350 VLNG500 VLNG750 VLNG1000, detail
est store a
 
#d;
esttab a using "$tables/LNG_desc.tex", replace
collabels(\multicolumn{1}{c}{{Mean}} \multicolumn{1}{c}{{SD}} \multicolumn{1}{l}{{Min}} \multicolumn{1}{l}{{P25}} \multicolumn{1}{l}{{Median}} \multicolumn{1}{l}{{P75}} \multicolumn{1}{l}{{Max}})
cells("mean(fmt(3)) sd(fmt(3)) min(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3)) max(fmt(3))") label nonumber f noobs alignment(S) booktabs
;
#d cr

** TABLE A2 - correlation r
* run correlations
corr VLNG100 VLNG200 VLNG350 VLNG500 VLNG750 VLNG1000

* store coefficients
forval r = 1(1)6 {
	forval c = 1(1)6 {
	
	local rho`r'`c' = string(r(C)[`r',`c'],"%04.3f")

}
}

* produce table 
cd "$tables"
local file "corr_lng.tex"
cap erase `file'
writeln `file' "LNG100 & 1   \\"
writeln `file' "LNG200 & `rho21' & 1 \\"
writeln `file' "LNG350 & `rho31' & `rho32' & 1 \\"
writeln `file' "LNG500 & `rho41' & `rho42' & `rho43' & 1 \\"
writeln `file' "LNG750 & `rho51' & `rho52' & `rho53' & `rho54' & 1 \\"
writeln `file' "LNG1000 & `rho61' & `rho62' & `rho63' & `rho64' & `rho65' & 1 \\"

** TABLE A3 - correlation space and value LNG
corr SLNG100 SLNG200 SLNG350 SLNG500 SLNG750 SLNG1000 VLNG100 VLNG200 VLNG350 VLNG500 VLNG750 VLNG1000

* store coefficients
forval r = 1(1)12 {
	forval c = 1(1)12 {
	
	local rho`r'`c' = string(r(C)[`r',`c'],"%04.3f")

}
}

* produce table 
cd "$tables"
local file "corr_lng_spaceval.tex"
cap erase `file'
writeln `file' "& LNG100 & `rho71' & `rho72' & `rho73' & `rho74' & `rho75' & `rho76' \\"
writeln `file' "& LNG200 & `rho81' & `rho82' & `rho83' & `rho84' & `rho85' & `rho86' \\"
writeln `file' "& LNG350 & `rho91' & `rho92' & `rho93' & `rho94' & `rho95' & `rho96' \\"
writeln `file' "& LNG500 & `rho101' & `rho102' & `rho103' & `rho104' & `rho105' & `rho106' \\"
writeln `file' "& LNG750 & `rho111' & `rho112' & `rho113' & `rho114' & `rho115' & `rho116' \\"
writeln `file' "& LNG1000  & `rho121' & `rho122' & `rho123' & `rho124' & `rho125' & `rho126'\\"

restore

}
********************************************************************************
* Table A4 - LNG determinants
********************************************************************************
{
preserve	

* load data at tract level
use "$data/int/LNG_08_900_CUSEC.dta", clear

* data to plot
keep if Year==2019
keep Year CPRO CMUN CDIS CSEC VLNG100* VLNG200* VLNG350* VLNG500* VLNG750* VLNG1000*

* add tract covariates - atlas renta year 2017
replace Year = 2017
local vars MedianHHInc MedianPersInc PopMeanAge Pop MeanHHSize
merge m:1 CPRO CMUN CDIS CSEC Year using "$data/int/ine_atlas_renta_csec.dta", keepusing(`vars')
keep if _merge == 3
drop _merge
replace Year = 2019

* registry covariates in 2015
g gender = "as"
g year = 2019

merge m:m CPRO CMUN CDIS CSEC gender year using "$data/int/reg_csec_2019.dta", keepusing(pop foreign)
drop if _merge==2
drop _merge
drop gender year

g shrforeign = foreign/pop

* building characteristics from catastro
local vars NBlngs MedNFloorsCSEC MedAptSizeCSEC MedYearConstCSEC MedQualCSEC ShrSqm* AreaSqm BARRI
merge m:1 CPRO CMUN CDIS CSEC Year using "$data/int/catastro_csec_chars.dta", keepusing(`vars')
keep if _merge == 3
drop _merge

* population density
g PopDensity = pop / AreaSqm

g ShrSqmCOM = ShrSqmCCSEC + ShrSqmGCCSEC + ShrSqmGHCSEC + ShrSqmGRCSEC
g ShrSqmEDU = ShrSqmECSEC + ShrSqmKCSEC
g lnMedAptSizeCSEC = ln(MedAptSizeCSEC)
g lnMedianHHInc = ln(MedianHHInc)

* vars to standardize
local outcomes VLNG100_mean VLNG200_mean VLNG350_mean VLNG500_mean VLNG750_mean VLNG1000_mean
local demvars lnMedianHHInc MeanHHSize PopDensity Pop PopMeanAge shrforeign
local catvars NBlngs lnMedAptSizeCSEC MedYearConstCSEC MedNFloorsCSEC MedAptSizeCSEC MedQualCSEC ShrSqmCOM ShrSqmEDU

* standardize
foreach var in `outcomes' `demvars' `catvars' {
	egen `var'SD = std(`var')
}

egen CDISFE = group(CDIS)

* label
la var lnMedianHHIncSD "Log Median HH Income"
la var MeanHHSizeSD "Median HH Size"
la var PopDensitySD "Population Density"
la var PopMeanAgeSD "Mean Population Age"
la var shrforeignSD "Share Foreign"
la var lnMedAptSizeCSECSD "Median Apartment Size"
la var MedQualCSECSD "Median Apartment Quality"
la var MedYearConstCSEC "Median Construction Year"
la var MedNFloorsCSECSD "Median Number of Floors"

global options r cluster(BARRI)

* now run regressions
local demvars lnMedianHHIncSD MeanHHSizeSD PopDensitySD PopMeanAgeSD shrforeignSD
local catvars lnMedAptSizeCSECSD MedQualCSECSD MedYearConstCSEC MedNFloorsCSECSD 
local varstokeep `demvars' `catvars'

* clear tables
eststo clear 
local varthx 24

foreach dist in 100 200 350 500 750 1000 {
	
	local outcome VLNG`dist'_mean
		
eststo: reg `outcome'SD `varstokeep' i.CDISFE, $options
		format `outcome'SD %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local FE "X"
		
}

* generate table
#d;
esttab using "$tables/LNG_Det.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3) noomitted
		stats (LNG mean SD r2 N FE, fmt(0 3 3 3 0) label("r (meters)" "Dep Var Mean" "Dep Var SD" "R2" "N" "District FE")) se 
		mgroups("Local Neighborhood Gini (LNG)", pattern(1 0 0 0 0 0 )
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

restore	
}
********************************************************************************
* Table A5: inequality comparison
********************************************************************************
{

preserve

foreach city in 08_900 28_900 46_900 50_900 41_900 07_40 35_17 30_30 {

	* which city?
	display "`city'"

	use "$data/int/RelIneqWBuffYears_`city'.dta", clear

	* space LNG
	sum Gini [fw = Properties] if Year==2019 & Buffer==100
	
	* for BCN, also check value
	if "`city'" == "08_900" {
		
		use "$data/int/RelIneqWValBuffYears_`city'.dta", clear

		sum Gini [fw = Properties] if Year==2019 & Buffer==100
		
		* value
		use "$data/int/PredPriceForest_08_900.dta", clear
		
		* compute ineq
		ineqdecgini PHat2019
		
	}
	
	* space
	use "$data/int/`city'_clus.dta", clear
	keep if Apartment==1|House==1
	
	* compute ineq
	ineqdecgini PropSqm

}	

restore

}
********************************************************************************
* Table B1 - sample vs bcn
********************************************************************************
{
preserve

* pop avgs
import excel "$orig/aj_barcelona/bcn_sum.xlsx", sheet("Sheet1") firstrow clear

forval i = 1(1)12 {
	
	local varname = variable[`i']
	g `varname' = value[`i'] 
}

keep if _n == 1
drop variable value source
g actual = 1

* add survey data
append using "$data/analysis_dataset.dta"

* keep relevant sample
keep $samplerest | actual == 1

* variables
replace Female = female if actual==1
replace Age = age if actual==1
replace ForeignBorn = foreign if actual==1
replace HHNum = hh_size if actual==1
replace IncHH = hh_income if actual==1
replace IncHH = IncHH/1000
replace Unemployed = unemployed if actual==1
replace University = university if actual==1
replace Renter = renter if actual==1
replace Married = married if actual==1
replace actual = 0 if actual==.
g Pop = pop if actual==0
replace Pop = pop if actual==1
g VoteLEFT = PSOE + PODEMOS + ERC + CUP
replace VoteLEFT = vote_left if actual == 1
g VoteRIGHT = JXCAT + PP + CS + VOX
replace VoteRIGHT= vote_right if actual == 1

* labels
la var Female "Female"
la var Age "Age"
la var IncHH "HH Income (1000s EUR)"
la var VoteLEFT "Voted a Left-wing Party"
la var VoteRIGHT "Voted a Right-wing Party"
la var Married "Married"
la var HHNum "HH Size"

**  program to get difference in means
capt prog drop myttests

program myttests, eclass
     syntax varlist [if] [in], by(varname) [ * ]
     marksample touse
     markout `touse' `by'
     tempname mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2
   foreach var of local varlist {
         qui ttest `var' if `touse', by(`by') `options'
         mat `mu_1' = nullmat(`mu_1'), r(mu_1)
         mat `mu_2' = nullmat(`mu_2'), r(mu_2)
		 mat `sd_1' = nullmat(`sd_1'), r(sd_1)
         mat `sd_2' = nullmat(`sd_2'), r(sd_2)
         mat `d'    = nullmat(`d'   ), r(mu_1) - r(mu_2)
         mat `d_se' = nullmat(`d_se'), r(se)
         mat `d_t'  = nullmat(`d_t' ), r(t)
         mat `d_p'  = nullmat(`d_p' ), r(p)
		 mat `n_1'  = nullmat(`n_1' ), r(N_1)
		 mat `n_2'  = nullmat(`n_2' ), r(N_2)
		 mat `se_1'  = nullmat(`se_1' ), r(sd_1)/((r(N_1))^(1/2))
		 mat `se_2'  = nullmat(`se_2' ), r(sd_2)/((r(N_2))^(1/2))
     }
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         mat coln ``mat'' = `varlist'
     }
    tempname b V
     mat `b' = `mu_1'*0
     mat `V' = `b''*`b'
     eret post `b' `V'
     eret local cmd "myttests"
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         eret mat `mat' = ``mat''
     }
end

** Table
local Population = Pop[_n==1]

#d;
	local varssum Female Age Married ForeignBorn University Renter Unemployed 
	IncHH HHNum VoteLEFT VoteRIGHT
	;
#d cr

* clear tables
eststo clear 
local varthx 24

* generate table
myttests `varssum', by(actual)

ereturn list

#d;
esttab using "$tables/Survey_SampleRep.tex", replace nonumbers noobs /*gaps*/
	cells("mu_1(fmt(%9.3f) label(Sample))  mu_2(fmt(%9.3f) label(Barcelona))d(star pvalue(d_p) fmt(3) label(Difference))" " se_1(par fmt(3) label((SE))) . .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none) /*this to remove column headers*/
	fragment
	;
#d cr

* number of observations
cap drop x
cap drop N
g x=1 if actual==0
egen N = total(x)
replace N = `Population' if actual==1

* clear tables
eststo clear 
local varthx 24

* generate table
myttests N, by(actual)

ereturn list

#d;
esttab using "$tables/Survey_SampleRep_N.tex",  
	replace nonumbers noobs nomtitles nodep nolines collabels(none)
	cells("mu_1(fmt(%9.0f)) mu_2(fmt(%9.0f))")
	label varwidth(`varthx') wrap 
	fragment
	;
#d cr

drop N x

restore

}
********************************************************************************
* Table B3 - Determinants of Perc Ineq & Pref Red
********************************************************************************
{

* label
la var PercGiniSD "Perceived Gini"
la var lnIncHHSD "Log HH Income"
la var HHNumSD "HH Size"
la var AgeSD "Age"

* locals
local varstokeep PercGiniSD Female AgeSD Married ForeignBorn University Renter Unemployed lnIncHHSD HHNumSD Religious Left

	* clear tables
	eststo clear 
	local varthx 24

foreach outcome in PercGini PrefRedScaled {
	
	replace outcome = `outcome'SD

	* controls
	eststo:	reg outcome  $controlsNoSD $contSD $samplerest , $options
		format `outcome'SD %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Controls "X"
		estadd local FE ""

	* controls and FE
	eststo:	reg outcome $controlsNoSD $contSD $fe $samplerest , $options
		format `outcome'SD %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Controls "X"
		estadd local FE "X"
		

	if "`outcome'" == "PrefRedScaled" {
	
	* controls and FE
	eststo:	reg outcome PercGiniSD $controlsNoSD $contSD $fe $samplerest , $options
		format `outcome'SD %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Controls "X"
		estadd local FE "X"
	
	}

}

* generate table
#d;
esttab using "$tables/Survey_PredRed_Gini_Det_Main_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep' ) 
		keep(`varstokeep' )
		nomtitles b(3)
		noomitted
		stats (mean SD r2 N FE, fmt(3 3 3 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "District FE")) se
		mgroups("Perceived Gini" "Pref for Redistribution", pattern(1 0 1 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}
********************************************************************************
* Table B4 - perceptions and pref red
********************************************************************************
{

* label
la var PercGiniSD "Perceived Gini"
la var lnIncHHSD "log HH Income"
la var MobilityPoorQ1Q1SD "Perceived Mobility Q1-Q1"
la var MobilityPoorQ1Q5SD "Perceived Mobility Q1-Q5"
la var ImmPercCtrySD "Perceived Immigration"
la var MobilityPoorQ1Q1SD "Perceived Lack of Mobility"
la var MobilityPoorQ1Q5SD "Perceived Upward Mobility"
la var LuckSD "Luck"
la var TrustPolSD "Trust in Politicians"

	* clear tables
	eststo clear 
	local varthx 24
	
local determinants PercGiniSD ImmPercCtrySD MobilityPoorQ1Q5SD MobilityPoorQ1Q1SD LuckSD TrustPolSD
local varstokeep `determinants'

foreach outcome in PrefRedScaled {

* one det at a time
foreach det in `determinants' {

	eststo:	reg `outcome'SD `det' $controlsDes $fe $samplerest , $options
		format `outcome'SD %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Controls "X"
		estadd local FE "X"
		
}

* all determinants together + controls and FE
eststo:	reg `outcome'SD `determinants' $controlsDes $fe $samplerest , $options

		format `outcome'SD %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Controls "X"
		estadd local FE "X"

}

* generate table
#d;
esttab using "$tables/Survey_PredRed_Det_rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep' ) 
		keep(`varstokeep' )
		nomtitles b(3)
		noomitted
		stats (mean SD r2 N Controls FE, fmt(3 3 3 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Controls" "District FE")) se
		mgroups("Preferences for Redistribution", pattern(1 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}	
********************************************************************************
* Table B5 - sorting
********************************************************************************
{

la var AgeSD "Age"
la var lnIncHHSD "log HH Income"
la var HHNumSD "HH Size"

local varstokeep $controlsNoSD $contSD

* clear tables
eststo clear 
local varthx 24

foreach dist in 100 200 350 500 750 1000 {
	
	* independent variable
	local outcome VLNG`dist'
		
* reg
eststo: reg `outcome'SD $controlsNoSD $contSD $fe $samplerest, $options
		format `outcome'SD %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local Controls "X"
		estadd local AddControls "X"
		estadd local FE "X"
		
}

* generate table
#d;
esttab using "$tables/Survey_VLNGDist_Sorting_rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3) noomitted
		stats (LNG mean SD r2 N FE, fmt(0 3 3 3 0) label("r (meters)" "Dep Var Mean" "Dep Var SD" "R2" "N" "District FE")) se 
		mgroups("Local Neighborhood Gini (LNG)", pattern(1 0 0 0 0 0 )
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}
********************************************************************************
* Table B6 - covariate balance
********************************************************************************
{
** program to get difference in means
capt prog drop myttests

program myttests, eclass
     syntax varlist [if] [in], by(varname) [ * ]
     marksample touse
     markout `touse' `by'
     tempname mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2
   foreach var of local varlist {
         qui ttest `var' if `touse', by(`by') `options'
         mat `mu_1' = nullmat(`mu_1'), r(mu_1)
         mat `mu_2' = nullmat(`mu_2'), r(mu_2)
		 mat `sd_1' = nullmat(`sd_1'), r(sd_1)
         mat `sd_2' = nullmat(`sd_2'), r(sd_2)
         mat `d'    = nullmat(`d'   ), r(mu_2) - r(mu_1)
         mat `d_se' = nullmat(`d_se'), r(se)
         mat `d_t'  = nullmat(`d_t' ), r(t)
         mat `d_p'  = nullmat(`d_p' ), r(p)
		 mat `n_1'  = nullmat(`n_1' ), r(N_1)
		 mat `n_2'  = nullmat(`n_2' ), r(N_2)
		 mat `se_1'  = nullmat(`se_1' ), r(sd_1)/((r(N_1))^(1/2))
		 mat `se_2'  = nullmat(`se_2' ), r(sd_2)/((r(N_2))^(1/2))
     }
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         mat coln ``mat'' = `varlist'
     }
    tempname b V
     mat `b' = `mu_1'*0
     mat `V' = `b''*`b'
     eret post `b' `V'
     eret local cmd "myttests"
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         eret mat `mat' = ``mat''
     }
end

** table
la var Renter "Renter"
la var HHNum "HH Size"

* rest sample
local SAMPLEREST $samplerest & PropYears >= 5

* income in 1000s
cap g HHInc1000S = IncHH / 1000
la var HHInc1000S "HH Income (1000s EUR)"

* vars to summarize	
#d;
	local varssum Female Age Married ForeignBorn University Renter Unemployed HHInc1000S HHNum Religious Left
	;
#d cr

* personal controls
	eststo clear 
	local varthx 24

myttests `varssum' `SAMPLEREST', by(T350_3Yrs)

ereturn list

#d;
esttab using "$tables/QE_Survey_DiffMeans_Revision_Pers_350m.tex", replace nonumbers noobs $stars
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none)
	fragment
	;
#d cr

* F test
reg T350_3Yrs `varssum' `SAMPLEREST'
local Ftest = string(e(F),"%04.3f")
local pval = (Ftail(e(df_m), e(df_r), e(F)))
pStars `pval'
cd "$tables"
local file "QE_Survey_DiffMeans_Ind_F.tex"
cap erase `file'
writeln `file' "F-test & & & `Ftest'\sym{`s(pStar)'}"

* neighborhood controls
la var VLNG350_2015 "LNG"
la var shrforeign_2015 "Share Foreign"
la var PctVotesLEFT_2015 "Left-wing Vote Share"
la var MedAptSizeCSEC_2015 "Median Apartment Size"
la var MedQualCSECScaled_2015 "Median Apartment Quality"
la var MedYearConstCSEC_2015 "Median Construction Year"
la var DistMetro "Closest Metro Station" 
la var DistPark "Closest Park"
la var DistSchool "Closest School"
la var DistHosp "Closest Hospital"

#d;
	local varssum VLNG350_2015 shrforeign_2015 PctVotesLEFT_2015 PopDensity_2015
	MedAptSizeCSEC_2015 MedQualCSECScaled_2015 MedYearConstCSEC_2015 DistMetro DistPark DistSchool DistHosp
	;
#d cr

	eststo clear 
	local varthx 24

* table
myttests `varssum' `SAMPLEREST', by(T350_3Yrs)

ereturn list

#d;
esttab using "$tables/QE_Survey_DiffMeans_Revision_Nhood_350m.tex", replace nonumbers noobs $stars
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none)
	fragment
	;
#d cr

* F test
reg T350_3Yrs `varssum' `SAMPLEREST'
local Ftest = string(e(F),"%04.3f")
local pval = (Ftail(e(df_m), e(df_r), e(F)))
pStars `pval'
cd "$tables"
local file "QE_Survey_DiffMeans_Neigh_F.tex"
cap erase `file'
writeln `file' "F-test & & & `Ftest'\sym{`s(pStar)'}"

* number of observations
cap drop x
cap drop N
g x=1 `SAMPLEREST'

bys T350_3Yrs: egen N = total(x)

	eststo clear 
	local varthx 24

* table
myttests N , by(T350_3Yrs)

ereturn list

#d;
esttab using "$tables/QE_Survey_DiffMeans_Revision_350m_N.tex",  
	replace nonumbers noobs nomtitles nodep nolines collabels(none)
	cells("mu_2(fmt(%9.0f)) mu_1(fmt(%9.0f))")
	label varwidth(`varthx') wrap 
	fragment
	;
#d cr

drop x N

}	
********************************************************************************
* Tables B7 & B8 - QE heterogeneity
********************************************************************************
{

cap la drop Univ AbInc AbAge Mar Un Rel For

la def Univ 1 "University"
la def AbInc 1 "Above Med Inc"
la def AbAge 1 "Above Age 45"
la def Mar 1 "Married"
la def Un 1 "Unemployed"
la def Rel 1 "Religious"
la def For 1 "Foreign Born"

cap g AbMedInc = (IncRankAct >= 0.5)
cap g AbMedAge = (Age >= 45)

la val University Univ
la val AbMedInc AbInc
la val AbMedAge AbAge
la val ForeignBorn For
la val Religious Rel
la val Married Mar
la val Unemployed Un

cap g trlast3 = .
la var trlast3 "New Building"
la val trlast3 BldngShock

* for regressions with interactions
local cont HHNumSD PopDensity_2015SD lnMedAptSizeCSEC_2015SD $contTract

#d;
local varstokeep 1.trlast3 
	1.trlast*1.Left 1.trlast*1.University 1.trlast*1.Renter 1.trlast*1.AbMedInc 
	1.trlast*1.AbMedAge 1.trlast*1.Married 1.trlast*1.Religious  1.trlast*1.ForeignBorn 
	1.trlast*1.Female
	;
#d cr
local dummycontrols i.Left i.University i.AbMedInc i.AbMedAge
global controlsSD2 Female Married ForeignBorn Religious Renter Unemployed

foreach outcome in PercGini PrefRedScaled {

	* clear tables
	eststo clear 
	local varthx 24

	if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
		replace trlast3 = T350_3Yrs
	}
	else if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"
		replace trlast3 = T350_3Yrs
	}
	
	* outcome
	replace outcome = `outcome'SD
	
	* controls
	eststo: reg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= 5  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= 5 ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		lincom _b[1.trlast3]
		local betaDif = r(estimate) 	
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
	
	foreach var in Left University Renter AbMedInc AbMedAge Married Religious ForeignBorn Female {
		
	* controls + interaction
	eststo: reg outcome i.trlast3##i.`var' `dummycontrols' $controlsSD2 `cont' $fe $samplerest & PropYears >= 5  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= 5 ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		lincom _b[1.trlast3] + _b[1.trlast3#1.`var']
		local betaDif = r(estimate) 	
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
		
	} 

* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_Het9_rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats (SumTest BetaSE mean SD r2 N Controls TractControls FE, fmt(3 3 3 3 3 0 0 0) label("Sum Treat Eff" " " "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE")) se
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

	}

}
********************************************************************************
* Tables B9 & B10 - alternative id strategies
********************************************************************************
{

cap g trlast3 = .
la val trlast3 BldngShock

local varstokeep 1.trlast3

foreach ID in BASELINE RING HOLE {
foreach outcome in PercGini PrefRedScaled {

	if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
	}
	else if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"
	}
	
	* clear tables
	eststo clear 
	local varthx 24

	if "`ID'" == "BASELINE" {
		local tablenotes stats (mean SD r2 N, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N")) se
		local addopts nonumbers mlabels(none) collabels(none) nomtitles nodep nolines
		local addopts2 mgroups("", prefix(\multicolumn{@span}{c}{) suffix(}) span )
		local addrest
	}
	else if "`ID'" == "RING" {
		local tablenotes stats (mean SD r2 N, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N")) se 
		local addopts nonumbers mlabels(none) collabels(none) nolines
		local addopts2 mgroups("", prefix(\multicolumn{@span}{c}{) suffix(}) span )

	}
	else if "`ID'" == "HOLE" {
		local tablenotes stats (Dist OutR mean SD r2 N Controls TractControls FE, fmt(0 0 3 3 3 0 0 0 0) label("Inner Ring (meters)" "Outer Ring (meters)" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE")) se
		local addopts nonumbers mlabels(none) collabels(none) nolines
		local addopts2 mgroups("", prefix(\multicolumn{@span}{c}{) suffix(}) span)
	}

	* outcome
	replace outcome = `outcome'SD

foreach dist in 100 200 350 500 {

	if "`dist'" == "100" {
		local OutR 350
	}
	if "`dist'" == "200" {
		local OutR 500
	}
	else if "`dist'" == "350" {
		local OutR 750
	}
	else if "`dist'" == "500" {
		local OutR 1000
	}

	if "`dist'" == "100" & "`ID'" == "RING" {
		local addrest & (Min_TrDist_3Yrs <  350)
	}
	if "`dist'" == "200" & "`ID'" == "RING" {
		local addrest & (Min_TrDist_3Yrs <  500)
	}
	else if "`dist'" == "350" & "`ID'" == "RING" {
		local addrest & (Min_TrDist_3Yrs <  750)
	}
	else if "`dist'" == "500" & "`ID'" == "RING" {
		local addrest & (Min_TrDist_3Yrs <  1000)
	}
	else if "`dist'" == "100" & "`ID'" == "HOLE" {
		local addrest & (Min_TrDist_3Yrs < 100 |  Min_TrDist_3Yrs >  350)
	}
	else if "`dist'" == "200" & "`ID'" == "HOLE" {
		local addrest & (Min_TrDist_3Yrs < 200 |  Min_TrDist_3Yrs >  500)
	}
	else if "`dist'" == "350" & "`ID'" == "HOLE" {
		local addrest & (Min_TrDist_3Yrs < 350 |  Min_TrDist_3Yrs >  750)
	}
	else if "`dist'" == "500" & "`ID'" == "HOLE" {
		local addrest & (Min_TrDist_3Yrs < 500 |  Min_TrDist_3Yrs >  1000)
	}
	else if "`ID'" == "BASELINE" {
		local addrest
	}

	replace trlast3 = T`dist'_3Yrs

		* no controls
		eststo: reg outcome i.trlast3 $fe $samplerest & PropYears >= 5 `addrest', $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= 5 `addrest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Dist "`dist'"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local OutR "`OutR'"
	
	
		* yes controls
		eststo: reg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= 5 `addrest', $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= 5 `addrest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Dist "`dist'"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local OutR "`OutR'"
		
}

* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_`ID'_Rev2.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		`tablenotes'
		`addopts'
		`addopts2'	
;
#d cr

} 
}

}				
********************************************************************************
* Tables B11 & B12 - alternative time windows
********************************************************************************
{

* sample rest
foreach dist in 200 350 500 {

	cap drop Res`dist'Y1
	cap drop Res`dist'Y2
	cap drop Res`dist'Y3
	g Res`dist'Y1 = (TREAT`dist'_2017==0 & TREAT`dist'_2018==0| ((TREAT`dist'_2018==1|TREAT`dist'_2017==1) & TREAT`dist'_2019==1))
	g Res`dist'Y2 = (TREAT`dist'_2017==0| TREAT`dist'_2017==1 & T`dist'_2Yrs==1)
	g Res`dist'Y3 = 1
	cap g T`dist'_1Yrs = TREAT`dist'_2019

}

cap g TREAT = .
cap la def T1 1 "New Building (2019)"
cap la def T2 1 "New Building (2018-19)"
cap la def T3 1 "New Building (2017-19)"

local varstokeep 1.TREAT 

foreach ID in 3YRS 2YRS 1YRS {

foreach outcome in PercGini PrefRedScaled  {

	if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
	}
	else if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"
	}

	* clear tables
	eststo clear 
	local varthx 24


	if "`ID'" == "3YRS" {
		local addcontrols Treat InfoTreatNeigh
		local tablenotes stats (mean SD r2 N, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N")) se 
		la val TREAT T3
		local addopts nonumbers mlabels(none) collabels(none) nomtitles nodep nolines
		local addopts2 mgroups("", prefix(\multicolumn{@span}{c}{) suffix(}) span )
	}
	else if "`ID'" == "2YRS" {
		local addcontrols 
		local tablenotes stats (mean SD r2 N, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N")) se
		la val TREAT T2
		local addopts nonumbers mlabels(none) collabels(none) nomtitles nodep nolines
		local addopts2 mgroups("", prefix(\multicolumn{@span}{c}{) suffix(}) span )

	}
	else if "`ID'" == "1YRS" {
		local addcontrols InfoTreatNeigh
		local tablenotes stats (Dist mean SD r2 N Controls TractControls FE NoExp, fmt(0 3 3 3 0 0 0 0) label("Treatment Distance (m)" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE" "No Previous Exposure")) se
		la val TREAT T1
		local addopts nonumbers mlabels(none) collabels(none) nomtitles nodep nolines
		local addopts2 mgroups("", prefix(\multicolumn{@span}{c}{) suffix(}) span )
	}

	* outcome
	replace outcome = `outcome'SD

foreach dist in 200 350 500 {

	if "`ID'" == "1YRS" {
		replace TREAT = T`dist'_1Yrs
		local addrest & Res`dist'Y1==1
	}
	else if "`ID'" == "2YRS" {
		replace TREAT = T`dist'_2Yrs
		local addrest & Res`dist'Y2==1
	}
	else if "`ID'" == "3YRS" {
		replace TREAT = T`dist'_3Yrs
		local addrest /*nothing*/
	}
		
	* yes controls
	eststo: reg outcome i.TREAT $controlsQE $fe $samplerest & PropYears >= 5 , $options
	format outcome %9.2f 
	summ `outcome' $samplerest & PropYears >= 5 `addrest',  format
	scalar mean = r(mean)
	estadd scalar mean 
	scalar SD = r(sd)
	estadd scalar SD 
	estadd local Dist "`dist'"
	estadd local Controls "X"
	estadd local TractControls "X"
	estadd local FE "X"
	estadd local NoExp ""
	
	* yes controls + sample rest
	eststo: reg outcome i.TREAT $controlsQE $fe $samplerest & PropYears >= 5 `addrest', $options
	format outcome %9.2f
	summ `outcome' $samplerest & PropYears >= 5 `addrest',  format
	scalar mean = r(mean)
	estadd scalar mean 
	scalar SD = r(sd)
	estadd scalar SD 
	estadd local Dist "`dist'"
	estadd local Controls "X"
	estadd local TractControls "X"
	estadd local FE "X"
	estadd local NoExp "X"
		
}

* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_`ID'_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		`tablenotes'
		`addopts'
		`addopts2'
		
;
#d cr

} 
}

}
********************************************************************************
* Table C1 - covariate balance info treat
********************************************************************************
{
**  program to get difference in means
capt prog drop myttests

program myttests, eclass
     syntax varlist [if] [in], by(varname) [ * ]
     marksample touse
     markout `touse' `by'
     tempname mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2
   foreach var of local varlist {
         qui ttest `var' if `touse', by(`by') `options'
         mat `mu_1' = nullmat(`mu_1'), r(mu_1)
         mat `mu_2' = nullmat(`mu_2'), r(mu_2)
		 mat `sd_1' = nullmat(`sd_1'), r(sd_1)
         mat `sd_2' = nullmat(`sd_2'), r(sd_2)
         mat `d'    = nullmat(`d'   ), r(mu_2) - r(mu_1)
         mat `d_se' = nullmat(`d_se'), r(se)
         mat `d_t'  = nullmat(`d_t' ), r(t)
         mat `d_p'  = nullmat(`d_p' ), r(p)
		 mat `n_1'  = nullmat(`n_1' ), r(N_1)
		 mat `n_2'  = nullmat(`n_2' ), r(N_2)
		 mat `se_1'  = nullmat(`se_1' ), r(sd_1)/((r(N_1))^(1/2))
		 mat `se_2'  = nullmat(`se_2' ), r(sd_2)/((r(N_2))^(1/2))
     }
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         mat coln ``mat'' = `varlist'
     }
    tempname b V
     mat `b' = `mu_1'*0
     mat `V' = `b''*`b'
     eret post `b' `V'
     eret local cmd "myttests"
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         eret mat `mat' = ``mat''
     }
end

** Table
la var Renter "Renter"
la var HHNum "HH Size"

* sample
local AddRest & (NeighPCorr==1 & TimeNeighprime>20|InfoTreatNeigh==0)
local SAMPLEREST $samplerest `AddRest'

* income in 1000s
cap g HHInc1000S = IncHH / 1000
la var HHInc1000S "HH Income (1000s EUR)"
	
#d;
	local varssum Female Age Married ForeignBorn University Renter Unemployed HHInc1000S HHNum Religious Left
	;
#d cr

* personal controls
	eststo clear 
	local varthx 24

* table
myttests `varssum' `SAMPLEREST', by(InfoTreatNeigh)

ereturn list

#d;
esttab using "$tables/InfoT_DiffMeans_Revision_Pers.tex", replace nonumbers noobs
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none)
	fragment
	;
#d cr

* neighborhood controls
la var shrforeign_2015 "Share Foreign"
la var PctVotesLEFT_2015 "Left-wing Vote Share"
la var PopDensity_2015 "Population Density"
la var MedAptSizeCSEC_2015 "Median Apartment Size"
la var MedQualCSECScaled_2015 "Median Apartment Quality"
la var MedYearConstCSEC_2015 "Median Construction Year"

#d;
	local varssum VLNG350_2015 shrforeign_2015 PctVotesLEFT_2015 PopDensity_2015
	MedAptSizeCSEC_2015 MedQualCSECScaled_2015 MedYearConstCSEC_2015
	;
#d cr

	eststo clear 
	local varthx 24

* table
myttests `varssum' `SAMPLEREST', by(InfoTreatNeigh)

ereturn list

#d;
esttab using "$tables/InfoT_DiffMeans_Revision_Nhood.tex", replace nonumbers noobs
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none)
	fragment
	;
#d cr

* number of observations
cap drop x
cap drop N
g x=1 `SAMPLEREST'

bys InfoTreatNeigh: egen N = total(x)

	eststo clear 
	local varthx 24

* table
myttests N , by(InfoTreatNeigh)

ereturn list

#d;
esttab using "$tables/InfoT_DiffMeans_Revision_N.tex",  
	replace nonumbers noobs nomtitles nodep nolines collabels(none)
	cells("mu_2(fmt(%9.0f)) mu_1(fmt(%9.0f))")
	label varwidth(`varthx') wrap 
	fragment
	;
#d cr

drop x N
	
}	
********************************************************************************
* Table C2 - info treat main
********************************************************************************
{

local AddRest & (NeighPCorr==1 & TimeNeighprime>20|InfoTreatNeigh==0)
local varstokeep 1.InfoTreatNeigh

	* clear tables
	eststo clear 
	local varthx 24
	
foreach outcome in PercGini PrefRedScaled {

	if "`outcome'" == "PrefRedScaled" {
		local addcontrols Treat 
		local tit "Preferences for Redistribution"
		local addopts
		local tableout2 erepeat(\cmidrule(lr){@span})
		local tableout mean SD r2 N Controls TractControls, fmt(3 3 3 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls")
	}
	else if "`outcome'" == "PercGini" {
		local addcontrols 
		local tit "Perceived Gini"
		local addopts
		local tableout2 erepeat(\cmidrule(lr){@span})
		local tableout mean SD r2 N Controls TractControls, fmt(3 3 3 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" )
	}

	* outcome
	replace outcome = `outcome'SD	
	
* no controls
eststo: reg outcome i.InfoTreatNeigh $samplerest `AddRest' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest `AddRest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE ""
		estadd local SampleR "X"
			
* yes controls
eststo: reg outcome i.InfoTreatNeigh $controlsQE $samplerest `AddRest' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest `AddRest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE ""
		estadd local SampleR "X"	
	
	} 
	
* generate table
#d;
esttab using "$tables/Survey_TreatNPrime_PrefRedGini_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3) noomitted
		stats(`tableout') se `addopts'
		mgroups("Perceived Gini" "Pref Redistribution", pattern(1 0 1 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span `tableout2')
;
#d cr

}
********************************************************************************
* Table C3 - info treat perc income
********************************************************************************
{
	
foreach i in 10 30 50 70 90 99 {
	cap g lnIncp`i' = ln(IncTilesPerc_p`i' + 1)
}
	
local tilesrest & (TimeIncTiles > 50 & TimeIncTiles < 440)
local AddRest & (NeighPCorr==1 & TimeNeighprime>20|InfoTreatNeigh==0)
local varstokeep 1.InfoTreatNeigh

	* clear tables
	eststo clear 
	local varthx 24

foreach outcome in lnIncp99 lnIncp90 lnIncp70 lnIncp50 lnIncp30 lnIncp10 {

	local addcontrols 
	local tableout mean SD r2 N Controls TractControls, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls")
	local tit ("Perceived P99" "Perceived P90" "Perceived P70" "Perceived P50" "Perceived P30" "Perceived P10", pattern(1 0 1 0 1 0 1 0 1 0 1 0)
	local addopts 
	local addtabopts erepeat(\cmidrule(lr){@span})

	* outcome
	replace outcome = `outcome'SD
	
	* no controls
eststo: reg outcome i.InfoTreatNeigh $samplerest `AddRest' , $options
	summ `outcome' $samplerest `AddRest' ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls ""
		estadd local TractControls ""
	
	* yes controls
eststo: reg outcome i.InfoTreatNeigh $controlsQE $samplerest `AddRest' , $options
	summ `outcome' $samplerest `AddRest' ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
	
} 

* generate table
#d;
esttab using "$tables/Survey_TreatNPrime_PercInc_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats (`tableout') se `addopts'
		mgroups`tit'
		prefix(\multicolumn{@span}{c}{) suffix(}) span `addtabopts')
;
#d cr
	
}
********************************************************************************
* Table C4 - info treat het district
********************************************************************************
{

local varstokeep 1.InfoTreatNeigh 1.BelowMDis 1.InfoTreatNeigh#1.BelowMDis

	eststo clear 
	local varthx 24
	
	local AddRest & (NeighPCorr==1 & TimeNeighprime>20|InfoTreatNeigh==0)
	
foreach outcome in PercGini PrefRedScaled {

	if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"
		local addopts
		local tableout2 erepeat(\cmidrule(lr){@span})
		local tableout SumTest BetaSE mean SD r2 N Controls TractControls, fmt(3 3 3 3 3 0 0 0) label("Sum of Treatment Effects" " " "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls")
	}
	else if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
		local addopts
		local tableout2 erepeat(\cmidrule(lr){@span})
		local tableout SumTest BetaSE mean SD r2 N Controls TractControls, fmt(3 3 3 3 3 0 0 0) label("Sum of Treatment Effects" " " "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls")
	}

	* outcome
	replace outcome = `outcome'SD	
		
* no controls
eststo: reg outcome i.InfoTreatNeigh i.BelowMDis $samplerest `AddRest' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest `AddRest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE ""
		estadd local SampleR "X"		
		
* yes controls
eststo: reg outcome i.InfoTreatNeigh i.BelowMDis $controlsQE $samplerest `AddRest' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest `AddRest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE ""
		estadd local SampleR "X"

		
** include interaction
* no controls
eststo: reg outcome i.InfoTreatNeigh##i.BelowMDis $samplerest `AddRest', $options
		format outcome %9.2f 
		summ `outcome' $samplerest `AddRest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE ""
		estadd local SampleR "X"
		lincom _b[1.InfoTreatNeigh] + _b[1.InfoTreatNeigh#1.BelowMDis]
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
		
* yes controls
eststo: reg outcome i.InfoTreatNeigh##i.BelowMDis $controlsQE $samplerest `AddRest', $options
		format outcome %9.2f 
		summ `outcome' $samplerest `AddRest',  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE ""
		estadd local SampleR "X"
		lincom _b[1.InfoTreatNeigh] + _b[1.InfoTreatNeigh#1.BelowMDis]
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"

	} 
	
* generate table
#d;
esttab using "$tables/Survey_TreatNPrime_PrefRedGini_HetDist_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3) noomitted
		stats(`tableout') se `addopts'		
		mgroups("Perceived Gini" "Preferences for Redistribution", pattern(1 0 0 0 1 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span `tableout2')
;
#d cr
	
}
********************************************************************************
* Table C5 - info treat perc income het district
********************************************************************************
{

local tilesrest & (TimeIncTiles > 50 & TimeIncTiles < 440)
local pyramidrest & (NeighPCorr==1 & TimeNeighprime>20|InfoTreatNeigh==0)
local varstokeep 1.InfoTreatNeigh 1.BelowMDis 1.InfoTreatNeigh#1.BelowMDis

	eststo clear 
	local varthx 24
   
foreach tile in Top Bottom {

	if "`tile'" == "Top" {
		local percinc lnIncp99 lnIncp90 lnIncp70
	}
	else if "`tile'" == "Bottom" {
		local percinc lnIncp50 lnIncp30 lnIncp10
	}
	
foreach outcome in `percinc'   {

	local addcontrols 
	local tableout SumTest BetaSE mean SD r2 N Controls TractControls, fmt(3 3 3 3 3 0 0 0 0) label("Sum of Treatment Effects" " " "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls")
	local tit ("Perceived P99" "Perceived P90" "Perceived P70" "Perceived P50" "Perceived P30" "Perceived P10", pattern(1 0 1 0 1 0 1 0 1 0 1 0)
	local addopts 
	local addtabopts erepeat(\cmidrule(lr){@span})

	* outcome
	replace outcome = `outcome'SD

	* no int
eststo: reg outcome i.InfoTreatNeigh i.BelowMDis $controlsQE $samplerest `pyramidrest' , $options
	summ `outcome' $samplerest `pyramidrest' ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		
	* yes int
eststo: reg outcome i.InfoTreatNeigh##i.BelowMDis $controlsQE  $samplerest `pyramidrest', $options
	summ `outcome' $samplerest `pyramidrest',  format
	scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		lincom _b[1.InfoTreatNeigh] + _b[1.InfoTreatNeigh#1.BelowMDis]
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
	
	}
}

* generate table
#d;
esttab using "$tables/Survey_TreatNPrime_Inc_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats (`tableout') se `addopts'
		mgroups`tit'
		prefix(\multicolumn{@span}{c}{) suffix(}) span `addtabopts')
;
#d cr

}
********************************************************************************
* Table D3 - Conley SE
********************************************************************************
{

cap g trlast3 = .
la var trlast3 "New Building Treatment"
la val trlast3 BldngShock

drop if Lat==.

local varstokeep 1.trlast3

foreach outcome in PercGini PrefRedScaled {

	* clear tables
	eststo clear 
	local varthx 24
	
	if "`outcome'" == "PercGini" {
		replace trlast3 = T350_3Yrs
		local tit "Perceived Gini"
		local addopts
		local tableout mean SD r2, fmt(3 3 3) label("Dep Var Mean" "Dep Var SD" "R2")
	}
	else if "`outcome'" == "PrefRedScaled" {
		replace trlast3 = T350_3Yrs
		local tit "Preferences for Redistribution"
		local addopts
		local tableout cut mean SD r2 N Controls TractControls FE DwellYears Renters, fmt(0 3 3 3 0 0 0 0) label("Conley SE Dist Cutoff (m)" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE" "Years in Dwelling" "Sample")
	}
	
	* rest
	local DwellYears = 5

	replace outcome = `outcome'SD
	
	* Controls and FE
	foreach cut in 0.2 0.35 0.5 0.75 1 {
	local meters = `cut' * 1000
	
	* no controls
	eststo: acreg outcome i.trlast3  $fe $samplerest & PropYears >= `DwellYears'  & Lat!=., spatial latitude(Lat) longitude(Lon) dist(`cut')
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local cut "`meters'"
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "Full"
		
	* yes controls
	eststo: acreg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= `DwellYears' & Lat!=. , spatial latitude(Lat) longitude(Lon) dist(`cut')
		format outcome %9.2f 	
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local cut "`meters'"
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "Full"
		
	}

* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_Conley.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats ( `tableout') se `addopts'
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} 

}
********************************************************************************
* Tables D4 & D5 - alternative outcomes
********************************************************************************
{

cap g TREAT = .
la val TREAT BldngShock

local varstokeep 1.TREAT 

foreach outcome in lnPerc_ratio9010 lnPerc_ratio9050 PercGiniPyr PrefRed2 LeftWParty {

	* clear tables
	eststo clear 
	local varthx 24

	if "`outcome'" == "lnPerc_ratio9010" {
		local addopts
		local tablenotes mgroups("log Perceived 90/10 Income Ratio", pattern(1 0 0 0 0 0 0 0 0)
		local tablenotes2 mean SD r2 N, fmt(3 3 3 0 0 0) label("Dep Var Mean (Non-std)" "Dep Var SD" "R2" "N")
		local addtabopts erepeat(\cmidrule(lr){@span})

	}
	else if "`outcome'" == "lnPerc_ratio9050" {
		local addopts nonumbers mlabels(none) collabels(none)
		local tablenotes mgroups("log Perceived 90/50 Income Ratio", pattern(1 0 0 0 0 0 0 0 0)
		local tablenotes2 mean SD r2 N, fmt(3 3 3 0 0 0) label("Dep Var Mean (Non-std)" "Dep Var SD" "R2" "N")
		local addtabopts

	}
	else if "`outcome'" == "PercGiniPyr" {
		local addopts nonumbers mlabels(none) collabels(none)
		local tablenotes mgroups("Perceived Gini (Pyramid)", pattern(1 0 0 0 0 0 0 0 0)
		local tablenotes2 Dist mean SD r2 N Controls TractControls FE, fmt(0 3 3 3 0 0 0) label("Inner Ring" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE")
		local addtabopts
	}
	else if "`outcome'" == "PrefRed2" {
		local addopts
		local tablenotes mgroups("Preferences for Redistribution (No Trade-off)", pattern(1 0 0 0 0 0 0 0 0)
		local tablenotes2 mean SD r2 N, fmt(3 3 3 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N")
		local addtabopts erepeat(\cmidrule(lr){@span})
	}
	else if "`outcome'" == "LeftWParty" {
		local addopts nonumbers mlabels(none) collabels(none)
		local tablenotes mgroups("Voted a Left-wing Party", pattern(1 0 0 0 0 0 0 0 0)
		local tablenotes2 Dist mean SD r2 N Controls TractControls FE , fmt(0 3 3 3 0 0 0) label("Inner Ring" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE")
		local addtabopts
	}
	
	* outcome
	if "`outcome'" != "LeftWParty" {
		replace outcome = `outcome'SD
	}
	else if "`outcome'" == "LeftWParty" {
		replace outcome = `outcome'
	}
	
foreach dist in 200 350 500 {

	* treatment var
	replace TREAT = T`dist'_3Yrs
	
	* no controls
	eststo: reg outcome i.TREAT $fe $samplerest & PropYears >= 5 , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= 5,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Dist "`dist'"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local SampleR "Full"
	
	* yes controls
	eststo: reg outcome i.TREAT $controlsQE $fe $samplerest & PropYears >= 5 , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= 5,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Dist "`dist'"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local SampleR "Full"
		
	} 

* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_Controls_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3) `addopts'
		stats (`tablenotes2') se
		`tablenotes'
		prefix(\multicolumn{@span}{c}{) suffix(}) span `addtabopts')
;
#d cr

} 

}	
********************************************************************************
* Table D6 - alternative outcomes - agg electoral data
********************************************************************************
{

preserve

* load electoral data
use "$data/analysis_dataset_aggcsec.dta", clear

* demean controls
g lnMedAptSizeCSEC_2015 = ln(MedAptSizeCSEC_2015)
#d;
	local cont ShrFemale MeanAge ShrRentals ShrMarried ShrUniversity lnMedianHHInc ShrHHUISub
	PopDensity_2015 lnMedAptSizeCSEC_2015 
	MedQualCSECScaled_2015 MedYearConstCSEC_2015 shrforeign_2015 PctVotesLEFT_2015NatE VLNG350_wmean_2015
	DistMetro DistPark DistSchool DistHosp
	;
#d cr

foreach var in `cont' PctVotesLEFT {

	egen `var'SD = std(`var') if ElecYear==2019 & ElecMonth==11 

}	

* globals
global fe i.CDISFE
egen clusvar = group(BARRI)
g outcome = .
#d;
	global controlsAgg ShrFemaleSD MeanAgeSD ShrRentalsSD ShrMarriedSD ShrUniversitySD lnMedianHHIncSD ShrHHUISubSD
	PopDensity_2015SD lnMedAptSizeCSEC_2015SD
	MedQualCSECScaled_2015SD MedYearConstCSEC_2015SD shrforeign_2015SD PctVotesLEFT_2015NatESD  VLNG350_wmean_2015SD
	DistMetroSD DistParkSD DistSchoolSD DistHospSD

	;
#d cr

* variables to keep
cap g trlast3 = .
cap la drop BldngShock
la def BldngShock 1 "New Building"
la val trlast3 BldngShock
cap drop LeftSD
cap g LeftSD = .
la var LeftSD "Left Vote Share in Last Election"
	
** table
local varstokeep 1.trlast3 

foreach outcome in PctVotesLEFT {

	* clear tables
	eststo clear 
	local varthx 24

foreach dist in 200 350 500 {

	* treatment and outcome var
	replace trlast3 = T`dist'_3Yrs
	replace outcome = `outcome'SD
	
	* no controls
	eststo: reg outcome i.trlast3 $fe if ElecYear==2019 & ElecMonth==11 & ShrMarried!=. , $options
		format outcome %9.2f 
		summ `outcome' if ElecYear==2019 & ElecMonth==11  ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Dist "`dist'"
		estadd local Controls ""
		estadd local FE "X"
		estadd local SampleR "All"
		estadd local Election "Nat19"


	* yes controls
	eststo: reg outcome i.trlast3 $controlsAgg $fe if ElecYear==2019 & ElecMonth==11  , $options
		format outcome %9.2f 
		summ `outcome' if ElecYear==2019 & ElecMonth==11  ,  format
		scalar mean = r(mean)
		estadd scalar mean 
		scalar SD = r(sd)
		estadd scalar SD 
		estadd local Dist "`dist'"
		estadd local Controls "X"
		estadd local FE "X"
		estadd local SampleR "All"
		estadd local Election "Nat19"
		
	}
	
* generate table
#d;
esttab using "$tables/QE_`outcome'_Controls_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		nonumbers mlabels(none) collabels(none) nomtitles nodep 
		stats (Dist mean SD r2 N Controls FE, fmt(0 3 3 3 0 0 0 0 0) label("Inner Ring" "Dep Var Mean" "Dep Var SD" "R2" "N" "Controls" "District FE")) se
		mgroups("Left-wing Parties Vote Share", pattern(1 0 0 0 0 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span )	
;
#d cr

} 
		
restore

}
********************************************************************************
* Table D7 - covariate balance - stayers
********************************************************************************
{
** program to get difference in means
capt prog drop myttests

program myttests, eclass
     syntax varlist [if] [in], by(varname) [ * ]
     marksample touse
     markout `touse' `by'
     tempname mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2
   foreach var of local varlist {
         qui ttest `var' if `touse', by(`by') `options'
         mat `mu_1' = nullmat(`mu_1'), r(mu_1)
         mat `mu_2' = nullmat(`mu_2'), r(mu_2)
		 mat `sd_1' = nullmat(`sd_1'), r(sd_1)
         mat `sd_2' = nullmat(`sd_2'), r(sd_2)
         mat `d'    = nullmat(`d'   ), r(mu_2) - r(mu_1)
         mat `d_se' = nullmat(`d_se'), r(se)
         mat `d_t'  = nullmat(`d_t' ), r(t)
         mat `d_p'  = nullmat(`d_p' ), r(p)
		 mat `n_1'  = nullmat(`n_1' ), r(N_1)
		 mat `n_2'  = nullmat(`n_2' ), r(N_2)
		 mat `se_1'  = nullmat(`se_1' ), r(sd_1)/((r(N_1))^(1/2))
		 mat `se_2'  = nullmat(`se_2' ), r(sd_2)/((r(N_2))^(1/2))
     }
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         mat coln ``mat'' = `varlist'
     }
    tempname b V
     mat `b' = `mu_1'*0
     mat `V' = `b''*`b'
     eret post `b' `V'
     eret local cmd "myttests"
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         eret mat `mat' = ``mat''
     }
end

** Table
la var Renter "Renter"
la var HHNum "HH Size"

* define stayers
cap drop Stayer
g Stayer = (PropYears >= 5)

* sample rest
local SAMPLEREST $samplerest


cap g HHInc1000S = IncHH / 1000
la var HHInc1000S "HH Income (1000s EUR)"
	
#d;
	local varssum PercGini PrefRedScaled Female Age Married ForeignBorn University Renter Unemployed HHInc1000S HHNum Religious Left
	;
#d cr

* personal controls
	eststo clear 
	local varthx 24

* table
myttests `varssum' `SAMPLEREST', by(Stayer)

ereturn list

#d;
esttab using "$tables/QE_DiffMeans_Stayers_Ind.tex", replace nonumbers noobs $stars
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none)
	fragment
	;
#d cr

* F test
reg Stayer `varssum' `SAMPLEREST'
local Ftest = string(e(F),"%04.3f")
local pval = (Ftail(e(df_m), e(df_r), e(F)))
pStars `pval'
cd "$tables"
local file "QE_DiffMeans_Stayers_Ind_F.tex"
cap erase `file'
writeln `file' "F-test & & & `Ftest'\sym{`s(pStar)'}"

* neighborhood controls
la var VLNG350_2015 "LNG"
la var shrforeign_2015 "Share Foreign"
la var PctVotesLEFT_2015 "Left-wing Vote Share"
la var MedAptSizeCSEC_2015 "Median Apartment Size"
la var MedQualCSECScaled_2015 "Median Apartment Quality"
la var MedYearConstCSEC_2015 "Median Construction Year"
la var DistMetro "Closest Metro Station" 
la var DistPark "Closest Park"
la var DistSchool "Closest School"
la var DistHosp "Closest Hospital"

#d;
	local varssum VLNG350_2015 shrforeign_2015 PctVotesLEFT_2015 PopDensity_2015
	MedAptSizeCSEC_2015 MedQualCSECScaled_2015 MedYearConstCSEC_2015 
	DistMetro DistPark DistSchool DistHosp
	;
#d cr

	eststo clear 
	local varthx 24

* table
myttests `varssum' `SAMPLEREST', by(Stayer)

ereturn list

#d;
esttab using "$tables/QE_DiffMeans_Stayers_Nhood.tex", replace nonumbers noobs $stars
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none)
	fragment
	;
#d cr

* F test
reg Stayer `varssum' `SAMPLEREST'
local Ftest = string(e(F),"%04.3f")
local pval = (Ftail(e(df_m), e(df_r), e(F)))
pStars `pval'
cd "$tables"
local file "QE_DiffMeans_Stayers_Nhood_F.tex"
cap erase `file'
writeln `file' "F-test & & & `Ftest'\sym{`s(pStar)'}"

* number of observations
cap drop x
cap drop N
g x=1 `SAMPLEREST'

bys Stayer: egen N = total(x)

	eststo clear 
	local varthx 24

* table
myttests N , by(Stayer)

ereturn list

#d;
esttab using "$tables/QE_DiffMeans_Stayers_N.tex",  
	replace nonumbers noobs nomtitles nodep nolines collabels(none)
	cells("mu_2(fmt(%9.0f)) mu_1(fmt(%9.0f))")
	label varwidth(`varthx') wrap 
	fragment
	;
#d cr

drop x N

}	
********************************************************************************
* Table D8 - covariate balance - non-stayers: T vs C
********************************************************************************
{
**  program to get difference in means
capt prog drop myttests

program myttests, eclass
     syntax varlist [if] [in], by(varname) [ * ]
     marksample touse
     markout `touse' `by'
     tempname mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2
   foreach var of local varlist {
         qui ttest `var' if `touse', by(`by') `options'
         mat `mu_1' = nullmat(`mu_1'), r(mu_1)
         mat `mu_2' = nullmat(`mu_2'), r(mu_2)
		 mat `sd_1' = nullmat(`sd_1'), r(sd_1)
         mat `sd_2' = nullmat(`sd_2'), r(sd_2)
         mat `d'    = nullmat(`d'   ), r(mu_2) - r(mu_1)
         mat `d_se' = nullmat(`d_se'), r(se)
         mat `d_t'  = nullmat(`d_t' ), r(t)
         mat `d_p'  = nullmat(`d_p' ), r(p)
		 mat `n_1'  = nullmat(`n_1' ), r(N_1)
		 mat `n_2'  = nullmat(`n_2' ), r(N_2)
		 mat `se_1'  = nullmat(`se_1' ), r(sd_1)/((r(N_1))^(1/2))
		 mat `se_2'  = nullmat(`se_2' ), r(sd_2)/((r(N_2))^(1/2))
     }
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         mat coln ``mat'' = `varlist'
     }
    tempname b V
     mat `b' = `mu_1'*0
     mat `V' = `b''*`b'
     eret post `b' `V'
     eret local cmd "myttests"
     foreach mat in mu_1 mu_2 d d_se d_t d_p n_1 n_2 sd_1 sd_2 se_1 se_2 {
         eret mat `mat' = ``mat''
     }
end

** Table
la var Renter "Renter"
la var HHNum "HH Size"

* define stayers
cap drop Stayer
g Stayer = (PropYears >= 5)

* sample restriction
local SAMPLEREST $samplerest & Stayer==0

cap g HHInc1000S = IncHH / 1000
la var HHInc1000S "HH Income (1000s EUR)"
	
#d;
	local varssum PercGini PrefRedScaled Female Age Married ForeignBorn University Renter Unemployed HHInc1000S HHNum Religious Left
	;
#d cr

* personal controls
	eststo clear 
	local varthx 24

* table
myttests `varssum' `SAMPLEREST', by(T350_3Yrs)

ereturn list

#d;
esttab using "$tables/QE_DiffMeans_NonStayers_Ind.tex", replace nonumbers noobs $stars
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none) 
	fragment
	;
#d cr

* F test
reg T350_3Yrs `varssum' `SAMPLEREST'
local Ftest = string(e(F),"%04.3f")
local pval = (Ftail(e(df_m), e(df_r), e(F)))
pStars `pval'
cd "$tables"
local file "QE_DiffMeans_NonStayers_Ind_F.tex"
cap erase `file'
writeln `file' "F-test & & & `Ftest'\sym{`s(pStar)'}"

* neighborhood controls
la var VLNG350_2015 "LNG"
la var shrforeign_2015 "Share Foreign"
la var PctVotesLEFT_2015 "Left-wing Vote Share"
la var MedAptSizeCSEC_2015 "Median Apartment Size"
la var MedQualCSECScaled_2015 "Median Apartment Quality"
la var MedYearConstCSEC_2015 "Median Construction Year"
la var DistMetro "Closest Metro Station" 
la var DistPark "Closest Park"
la var DistSchool "Closest School"
la var DistHosp "Closest Hospital"


#d;
	local varssum VLNG350_2015 shrforeign_2015 PctVotesLEFT_2015 PopDensity_2015
	MedAptSizeCSEC_2015 MedQualCSECScaled_2015 MedYearConstCSEC_2015 
	DistMetro DistPark DistSchool DistHosp
	;
#d cr

	eststo clear 
	local varthx 24

* table
myttests `varssum' `SAMPLEREST', by(T350_3Yrs)

ereturn list

#d;
esttab using "$tables/QE_DiffMeans_NonStayers_Nhood.tex", replace nonumbers noobs $stars
	cells("mu_2(fmt(%9.3f) label(Treated)) mu_1(fmt(%9.3f) label(Control)) d($stars2 pvalue(d_p) fmt(3) label(Difference))" "se_2(par fmt(3) label((SE))) se_1(par fmt(3) label((SE))) .")
	label varwidth(`varthx') wrap 
	nomtitles nodep nolines collabels(none)
	fragment
	;
#d cr

* F test
reg T350_3Yrs `varssum' `SAMPLEREST'
local Ftest = string(e(F),"%04.3f")
local pval = (Ftail(e(df_m), e(df_r), e(F)))
pStars `pval'
cd "$tables"
local file "QE_DiffMeans_NonStayers_Nhood_F.tex"
cap erase `file'
writeln `file' "F-test & & & `Ftest'\sym{`s(pStar)'}"

* number of observations
cap drop x
cap drop N
g x=1 `SAMPLEREST'

bys T350_3Yrs: egen N = total(x)

	eststo clear 
	local varthx 24

* table
myttests N , by(T350_3Yrs)

ereturn list


#d;
esttab using "$tables/QE_DiffMeans_NonStayers_N.tex",  
	replace nonumbers noobs nomtitles nodep nolines collabels(none)
	cells("mu_2(fmt(%9.0f)) mu_1(fmt(%9.0f))")
	label varwidth(`varthx') wrap 
	fragment
	;
#d cr

drop x N

}	
********************************************************************************
* Figure D4 & Table D9 - treatment intensity
********************************************************************************
{
	
ta NT350_3Yrs $samplerest & PropYears >= 5

cap drop OneBlg OnePlusBlg
g OneBlg = (NT350_3Yrs==1)
g OnePlusBlg = (NT350_3Yrs>1)
	
** Figure D4
grstyle init
grstyle set color hue, n(2)
grstyle set imesh, horizontal compact minor
grstyle set legend 6, nobox
grstyle set symbol
grstyle set lpattern	

#d;
binscatter PercGini NT350_3Yrs $samplerest & PropYears >= 5,
xtit("Number of New Buildings")
ytit("Perceived Gini")
;
#d cr
graph export "$figs/scatter_nbldg_PercGini.pdf", replace

#d;
binscatter PrefRedScaled NT350_3Yrs $samplerest & PropYears >= 5,
xtit("Number of New Buildings")
ytit("Preferences for Redistribution")
;
#d cr
graph export "$figs/scatter_nbldg_PrefRed.pdf", replace

** Table D9: PercGini and PrefRed
la var OneBlg "One Building"
la var OnePlusBlg "More than One Building"

local varstokeep OneBlg OnePlusBlg

foreach outcome in PercGini PrefRedScaled {

	* clear tables
	eststo clear 
	local varthx 24

	
	if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
		local addopts
		local tableout mean SD r2, fmt(3 3 3) label("Dep Var Mean" "Dep Var SD" "R2")
	}
	else if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"
		local addopts
		local tableout mean SD r2 N Controls TractControls FE DwellYears Renters, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE" "Years in Dwelling" "Sample")
	}
	
	** years restriction
	foreach DwellYears in 5 10 15 {

	* no controls
	replace outcome = `outcome'SD 	
	
	eststo: reg outcome OneBlg OnePlusBlg  $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "Full"
		
	* yes controls
	eststo: reg outcome OneBlg OnePlusBlg $controlsQE $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "Full"
		
	}
	
	** renter/owner
	local DwellYears 5
	
	forval renter = 1(-1)0 {
	
		if `renter' == 1 {
			local rentalstat "Renters"
		}
		else if `renter' == 0 {
			local rentalstat "Owners"
		}
	
	replace outcome = `outcome'SD 
	
	* no controls	
	eststo: reg outcome OneBlg OnePlusBlg $fe $samplerest & PropYears >= `DwellYears' & Renter == `renter' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
		
	* yes controls
	eststo: reg outcome OneBlg OnePlusBlg $controlsQE $fe $samplerest & PropYears >= `DwellYears'  & Renter == `renter', $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
		
		
	} 
	
* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_350_OneT_Inten.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats ( `tableout') se `addopts'
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} 

}
********************************************************************************
* Table D10 - barri FE 
********************************************************************************
{
	
cap drop barri
destring BARRI, g(barri)

cap g trlast3 = .
la val trlast3 BldngShock

local varstokeep 1.trlast3

foreach outcome in PercGini PrefRedScaled {

	* clear tables
	eststo clear 
	local varthx 24
	
	if "`outcome'" == "PercGini" {
		replace trlast3 = T350_3Yrs
		local tit "Perceived Gini"
		local addopts
		local tableout mean SD r2, fmt(3 3 3) label("Dep Var Mean" "Dep Var SD" "R2")
	}
	else if "`outcome'" == "PrefRedScaled" {
		replace trlast3 = T350_3Yrs
		local tit "Preferences for Redistribution"
		local addopts
		local tableout mean SD r2 N Controls TractControls FE DwellYears Renters, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "Neighborhood FE" "Years in Dwelling" "Sample")
	}
	
	** years restriction
	foreach DwellYears in 5 10 15 {

	replace outcome = `outcome'SD 	
	
	* no controls
	eststo: reg outcome i.trlast3 $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE ""
		estadd local Renters "Full"
		
	* yes controls
	eststo: reg outcome i.trlast3 $controlsQE i.barri $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "Full"
		
	}
	
	** renter/owner
	local DwellYears 5
	
	forval renter = 1(-1)0 {
	
		if `renter' == 1 {
			local rentalstat "Renters"
		}
		else if `renter' == 0 {
			local rentalstat "Owners"
		}
	
	replace outcome = `outcome'SD 
	
	* no controls	
	eststo: reg outcome i.trlast3 $samplerest & PropYears >= `DwellYears' & Renter == `renter' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE ""
		estadd local Renters "`rentalstat'"
		
	* yes controls
	eststo: reg outcome i.trlast3 $controlsQE i.barri $samplerest & PropYears >= `DwellYears'  & Renter == `renter', $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
			
	} 
	
* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_350_OneT_BarriFE.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats ( `tableout') se `addopts'
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}
	
}
********************************************************************************
* Table D11 - placebo
********************************************************************************
{

cap drop T350_3Yrs_Placebo
g T350_3Yrs_Placebo = (TREAT350_2014==1|TREAT350_2015==1|TREAT350_2016==1)

cap g trlast3 = .
la var trlast3 "New Building (2014-16)"
cap la drop plac
la def plac 1 "New Building (2014-16)"
la val trlast3 plac

local varstokeep 1.trlast3

foreach outcome in PercGini PrefRedScaled {

	* clear tables
	eststo clear 
	local varthx 24
	
	if "`outcome'" == "PercGini" {
		replace trlast3 = T350_3Yrs_Placebo
		local tit "Perceived Gini"
		local addopts
		local tableout mean SD r2, fmt(3 3 3) label("Dep Var Mean" "Dep Var SD" "R2")
	}
	else if "`outcome'" == "PrefRedScaled" {
		replace trlast3 = T350_3Yrs_Placebo
		local tit "Preferences for Redistribution"
		local addopts
		local tableout mean SD r2 N Controls TractControls FE DwellYears Renters, fmt(3 3 3 0 0 0 0) label("Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE" "Years in Dwelling" "Sample")
	}
	
	** year rest
	foreach DwellYears in 5 10 15 {

	* no controls
	replace outcome = `outcome'SD 	
	
	eststo: reg outcome i.trlast3  $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "Full"
		
	* yes controls
	eststo: reg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "Full"
		
	} 
	
	** renter/owner
	local DwellYears 5
	
	forval renter = 1(-1)0 {
	
		if `renter' == 1 {
			local rentalstat "Renters"
		}
		else if `renter' == 0 {
			local rentalstat "Owners"
		}
	
	replace outcome = `outcome'SD 
	
	* no controls	
	eststo: reg outcome i.trlast3 $fe $samplerest & PropYears >= `DwellYears' & Renter == `renter' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
		
	* yes controls
	eststo: reg outcome i.trlast3 $controlsQE $fe $samplerest & PropYears >= `DwellYears'  & Renter == `renter', $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
			
	} 

* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_Placebo.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats ( `tableout') se `addopts'
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} /*outcome loop*/

}
********************************************************************************
* Tables D12 & D13 - LNG interaction with treatments
********************************************************************************
{

cap g LNG = .
la var LNG "LNG"

local TractCon $tractcont
local AddRest

foreach outcome in PercGini PrefRedScaled {

	if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
		local inter i.InfoTreatNeigh##c.LNG
		local linc _b[LNG] + _b[1.InfoTreatNeigh#c.LNG]
		local varstokeep LNG 1.InfoTreatNeigh#c.LNG
	}
	else if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"
		local inter i.InfoTreatNeigh##c.LNG i.InfoTreatInc##c.LNG
		local linc _b[LNG] + _b[1.InfoTreatNeigh#c.LNG] + _b[1.InfoTreatInc#c.LNG]
		local varstokeep LNG 1.InfoTreatNeigh#c.LNG 1.InfoTreatInc#c.LNG
	}

	replace outcome = `outcome'SD

	* clear tables
	eststo clear 
	local varthx 24
	
	foreach dist in 100 200 350 500 750 1000 { 
	
	replace LNG = VLNG`dist'SD
	
* no controls
eststo: reg outcome `inter' $fe $samplerest `AddRest', $options
		format outcome %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		lincom `linc'
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
		
* yes controls
eststo: reg outcome `inter' $controlsDes $fe $samplerest `AddRest', $options
		format outcome %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		lincom `linc'
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
			
		} 

* generate table
#d;
esttab using "$tables/Survey_vlngDist_`outcome'_Inter_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		noomitted
		keep(`varstokeep')
		nomtitles b(3)
		stats (SumTest BetaSE LNG mean SD r2 N Controls TractControls FE, fmt(3 3 0 3 3 3 0 0) label("LNG Total Effect" " " "r (meters)" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE")) se
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} 

}
********************************************************************************
* Tables D14 & D15 - QE interaction with treatments
********************************************************************************
{

cap g trlast3 = .
la var trlast3 "New Building"
la val trlast3 BldngShock

local varstokeep 1.trlast3

foreach outcome in PercGini PrefRedScaled  {

	* clear tables
	eststo clear 
	local varthx 24

	if "`outcome'" == "PrefRedScaled" {
		local inter i.InfoTreatNeigh##i.trlast3 i.InfoTreatInc##i.trlast3
		local linc _b[1.trlast3] + _b[1.InfoTreatNeigh#1.trlast3] + _b[1.InfoTreatInc#1.trlast3]
		local varstokeep 1.trlast3 1.InfoTreatNeigh#1.trlast3 1.InfoTreatInc#1.trlast3
		replace trlast3 = T350_3Yrs
		local tit "Preferences for Redistribution"
		local addopts
		local tableout SumTest BetaSE mean SD r2 N Controls TractControls FE DwellYears Renters, fmt(3 3 3 3 3 0 0 0 0) label("Bldng Treat Total Effect" " " "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE" "Years in Dwelling" "Sample")
	}
	else if "`outcome'" == "PercGini" {
		local inter i.InfoTreatNeigh##i.trlast3
		local linc _b[1.trlast3] + _b[1.InfoTreatNeigh#1.trlast3]
		local varstokeep 1.trlast3 1.InfoTreatNeigh#1.trlast3
		replace trlast3 = T350_3Yrs
		local tit "Perceived Gini"
		local addopts
		local tableout SumTest BetaSE mean SD r2 N Controls TractControls FE DwellYears Renters, fmt(3 3 3 3 3 0 0 0 0) label("Bldng Treat Total Effect" " " "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neigh Controls" "District FE" "Years in Dwelling" "Sample")
	}
	
	replace outcome = `outcome'SD
		
	** years rest
	foreach DwellYears in 5 10 15 {

		* no controls
		eststo: reg outcome i.trlast3 `inter' $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Dist "350"
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "Full"
		lincom `linc'
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
		
		* yes controls	
		eststo: reg outcome i.trlast3 `inter' $controlsQE $fe $samplerest & PropYears >= `DwellYears'  , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' ,  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Dist "350"
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "Full"
		lincom `linc'
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
		
		
	} 
	
	** renter/owner
	local DwellYears 5
	
	forval renter = 1(-1)0 {
	
		if `renter' == 1 {
			local rentalstat "Renters"
		}
		else if `renter' == 0 {
			local rentalstat "Owners"
		}

		* no controls
		eststo: reg outcome i.trlast3 `inter' $fe $samplerest & PropYears >= `DwellYears' & Renter == `renter' , $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Dist "350"
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
		lincom `linc'
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
		
		* yes controls
		eststo: reg outcome i.trlast3 `inter' $controlsQE $fe $samplerest & PropYears >= `DwellYears' & Renter == `renter', $options
		format outcome %9.2f 
		summ `outcome' $samplerest & PropYears >= `DwellYears' & Renter == `renter',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local Dist "350"
		estadd local DwellYears "`DwellYears'$+$"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		estadd local Renters "`rentalstat'"
		lincom `linc'
		local betaDif = r(estimate) 		
		local pval = 2*ttail(r(df),abs(r(estimate)/r(se) ))
		pStars `pval'
		local betaDifStar = string(`betaDif',"%04.3f")+"`s(pStar)'"
		local betaDifStarNOS = string(`betaDif',"%04.3f")
		estadd local SumTest "`betaDifStar$starsum'"
		local betaSE = r(se) 
		local betaSE2 = string(`betaSE',"%04.3f")
		estadd local BetaSE "(`betaSE2')"
		
	} 
	
* generate table
#d;
esttab using "$tables/Survey_QE_`outcome'_350_Inter_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats ( `tableout') se `addopts'
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}

}
********************************************************************************
* Tables D1 & D2 - slng & wlng
********************************************************************************
{

cap g LNG = .

local varstokeep LNG

foreach lng in SLNG WVLNG {

	if "`lng'" == "SLNG" {
		la var LNG "LNG (Space)"
	}
	else if "`lng'" == "WVLNG" {
		la var LNG "WLNG"
	}
	
	foreach outcome in PercGini PrefRedScaled {

	if "`outcome'" == "PercGini" {
		local tit "Perceived Gini"
		local tableout mean SD r2, fmt(3 3 3) label("Dep Var Mean" "Dep Var SD" "R2")
	}
	else if "`outcome'" == "PrefRedScaled" {
		local tit "Preferences for Redistribution"
		local tableout LNG mean SD r2 N Controls TractControls FE, fmt(0 3 3 3 0 0 0 0) label("r (meters)" "Dep Var Mean" "Dep Var SD" "R2" "N" "Indiv Controls" "Neighborhood Controls" "District FE")
	}
	
	replace outcome = `outcome'SD

	eststo clear 
	local varthx 24
	
	foreach dist in 100 200 350 500 750 1000 { /*distance loop*/
	
	replace LNG = `lng'`dist'SD
	
* no controls
eststo: reg outcome LNG $fe $samplerest `AddRest', $options
		format outcome %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local Controls ""
		estadd local TractControls ""
		estadd local FE "X"
		
* yes controls
eststo: reg outcome LNG $controlsDes $fe $samplerest `AddRest', $options
		format outcome %9.2f 
		summ `outcome',  format
		scalar mean = r(mean)
		scalar SD = r(sd)
		estadd scalar mean 
		estadd scalar SD 
		estadd local LNG "`dist'"
		estadd local Controls "X"
		estadd local TractControls "X"
		estadd local FE "X"
		
	}

* generate table
#d;
esttab using "$tables/Survey_`lng'Dist_`outcome'_Full_OneT_Rev.tex", replace fragment booktabs $stars
		label varwidth(`varthx') wrap 
		order(`varstokeep') 
		keep(`varstokeep')
		nomtitles b(3)
		stats (`tableout') se	
		mgroups("`tit'", pattern(1 0 0 0 0 0 0 0 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} 
} 

}
********************************************************************************
* Figures D1 & D2 - Specification curve
********************************************************************************
{
** prepare data
use "$data/temp/survanalysis_check_qe.dta", clear
save "$data/temp/spec_curve.dta", replace

** program
* specification curve demo by Hans H. Sievertsen h.h.sievertsen@bristol.ac.uk, 29/10-2019
clear
cap program drop specchart
program specchart
syntax varlist, [replace] spec(string)
	* save current data
	tempfile temp
	save "`temp'",replace
	* dataset to store estimates
	if "`replace'"!=""{
			clear
			gen beta=.
			gen se=.
			gen spec_id=.
			gen u95=.
			gen u90=.
			gen l95=.
			gen l90=.
			save "$data/temp/estimates_rev.dta",replace
	}	
	else{
		* load dataset
		use "$data/temp/estimates_rev.dta",clear
	}
	* add observation
	local obs=_N+1
	set obs `obs'
	replace spec_id=`obs' if _n==`obs'
	* store estimates
	replace beta =_b[`varlist'] if  spec_id==`obs'
	replace se=_se[`varlist']   if  spec_id==`obs'
	replace u95=beta+invt(e(df_r),0.975)*se if  spec_id==`obs'
	replace u90=beta+invt(e(df_r),0.95)*se if  spec_id==`obs'
	replace l95=beta-invt(e(df_r),0.975)*se  if  spec_id==`obs'
	replace l90=beta-invt(e(df_r),0.95)*se  if  spec_id==`obs'
	* store specification
	foreach s in `spec'{
		cap gen `s'=1 			if  spec_id==`obs'
		cap replace `s'=1 		 if  spec_id==`obs'
	}
		save "$data/temp/estimates_rev.dta",replace
	* restore dataset
	use `temp',clear
end

** run models
foreach outcome in PercGini PrefRedScaled {

* run regressions 
use "$data/temp/spec_curve.dta", clear

g OUTCOME = .

* treat var
cap drop TREAT
g TREAT = T350_3Yrs

cap g T200_1Yrs = TREAT200_2019
cap g T350_1Yrs = TREAT350_2019
cap g T500_1Yrs = TREAT500_2019

* outcome
replace OUTCOME = `outcome'SD

* main specification
reg OUTCOME TREAT $controlsQE Left $fe $samplerest & PropYears >= 5 , $options
specchart TREAT, spec(main cont ideol fixed dist350 year3 tenure5 BASELINE) replace

* alternative specs
foreach ID in BASELINE RING HOLE { 
foreach y in 1 2 3 {
foreach dist in 200 350 500 {
foreach tenure in 5 10 15 {

	* add rest
	local addrest

	* spec
	if "`dist'" == "200" & "`ID'" == "RING" {
		local addrest & (Min_TrDist_3Yrs <  500)
	}
	else if "`dist'" == "350" & "`ID'" == "RING" {
		local addrest & (Min_TrDist_3Yrs <  750)
	}
	else if "`dist'" == "500" & "`ID'" == "RING" {
		local addrest & (Min_TrDist_3Yrs <  1000)
	}
	else if "`dist'" == "200" & "`ID'" == "HOLE" {
		local addrest & (Min_TrDist_3Yrs < 200 |  Min_TrDist_3Yrs >  500)
	}
	else if "`dist'" == "350" & "`ID'" == "HOLE" {
		local addrest & (Min_TrDist_3Yrs < 350 |  Min_TrDist_3Yrs >  750)
	}
	else if "`dist'" == "500" & "`ID'" == "HOLE" {
		local addrest & (Min_TrDist_3Yrs < 500 |  Min_TrDist_3Yrs >  1000)
	}
	
	cap drop Res`dist'Y1
	cap drop Res`dist'Y2
	cap drop Res`dist'Y3
	g Res`dist'Y1 = (TREAT`dist'_2017==0 & TREAT`dist'_2018==0| ((TREAT`dist'_2018==1|TREAT`dist'_2017==1) & TREAT`dist'_2019==1))
	g Res`dist'Y2 = (TREAT`dist'_2017==0| TREAT`dist'_2017==1 & T`dist'_2Yrs==1)
	g Res`dist'Y3 = 1
	
	* year rest
	if "`y'" == "1" {
		local addrestY & Res`dist'Y1==1
	}
	else if "`y'" == "2" {
		local addrestY & Res`dist'Y2==1
	}
	else if "`y'" == "3" {
		local addrestY
	}

* update vars
replace OUTCOME = `outcome'SD
replace TREAT = T`dist'_`y'Yrs

** regressions
* only main effect
reg OUTCOME TREAT $samplerest & PropYears >= `tenure' `addrest' `addrestY', $options
specchart  TREAT, spec(dist`dist' year`y' tenure`tenure' `ID') 

* only FE
reg OUTCOME TREAT $fe $samplerest & PropYears >= `tenure' `addrest' `addrestY', $options
specchart  TREAT, spec(fixed dist`dist' year`y' tenure`tenure' `ID') 

* controls no ideology NO FE
reg OUTCOME TREAT $controlsQE $samplerest & PropYears >= `tenure' `addrest' `addrestY', $options
specchart  TREAT, spec(cont dist`dist' year`y' tenure`tenure' `ID') 

* all controls no ideology + FE
reg OUTCOME TREAT $controlsQE $fe $samplerest & PropYears >= `tenure' `addrest' `addrestY', $options
specchart  TREAT, spec(cont fixed dist`dist' year`y' tenure`tenure' `ID') 

* all controls including ideology NO FE
reg OUTCOME TREAT $controlsQE Left $samplerest & PropYears >= `tenure' `addrest' `addrestY', $options
specchart  TREAT, spec(cont ideol dist`dist' year`y' tenure`tenure' `ID') 

* all controls including ideology + fe
reg OUTCOME TREAT $controlsQE Left $fe $samplerest & PropYears >= `tenure' `addrest' `addrestY', $options
specchart  TREAT, spec(cont ideol fixed dist`dist' year`y' tenure`tenure' `ID') 

* renters
reg OUTCOME TREAT $controlsQE Left $fe $samplerest & PropYears >= `tenure' `addrest' `addrestY' & Renter == 1, $options
specchart  TREAT, spec(cont ideol fixed dist`dist' year`y' tenure`tenure' `ID' renter) 

* owners
reg OUTCOME TREAT $controlsQE Left  $fe $samplerest & PropYears >= `tenure' `addrest' `addrestY' & Renter == 0, $options
specchart  TREAT, spec(cont ideol fixed dist`dist' year`y' tenure`tenure' `ID' owner) 

} 
} 
} 
} 

* store results
use "$data/temp/estimates_rev.dta",clear
compress
save "$data/temp/estimates_`outcome'_rev.dta", replace

}
** generate figure - note: was run in STATA 14
foreach outcome in PercGini PrefRedScaled {

* load data
use "$data/temp/estimates_`outcome'_rev.dta",clear

if "`outcome'" == "PrefRedScaled" {
	local tit "Preferences for Redistribution"
}
else if "`outcome'" == "PercGini" {
	local tit "Perceived Gini"
}

* only with fe
drop if fixed==.
* full sample
drop if renter == 1 | owner == 1
* RF indicator
g RF = 1
* controls including ideology only
g CONTROLS = 1 if (cont==1 & ideol==1)
duplicates drop main CONTROLS fixed dist* year* tenure* BASELINE RING HOLE, force

* how many specifications?
count
* how many positive coefficients?
count if beta > 0
* what is the smallest and average beta?
sum beta
* how many are significant?
count if l90>0
count if l95>0

* censor at 1.4 to fit the graph 
replace beta = 1.4 if beta > 1.4 & beta != .

* sort specifications
gsort -CONTROLS -fixed ///
	-dist200 -dist350 -dist500 ///
	-year3 -year2 -year1 ///
	-BASELINE -RING -HOLE ///
	-tenure5 -tenure10 -tenure15, mfirst
sort beta
* rank
gen rank=_n

* in what position is the baseline?
ta rank if main==1

* maxrank
scalar maxrank = _N
scalar medrank = _N/2
* max 100 obs
g SAMPLE = 1 if (rank < 25| rank >= maxrank - 25 | ((rank >= (medrank - 25)) & (rank <= (medrank + 25)))| main==1 )
keep if SAMPLE == 1
* update
drop rank
sort beta 
g rank = _n

* if main in rank = 25
g x = (rank==25 & main==1)
egen totx = max(x)
drop if rank==76 & totx==1
drop x totx
replace rank = _n

* bounds
local SCALE -0.2(0.2)1.4
local INITIAL -0.5
local JUMP 0.05
local JUMP2 0.05

* define locals for jumps
local l0 = `INITIAL'

forval i = 1(1)18 {

	local j = `i' - 1
	local l`i' = `l`j'' - `JUMP'

}

** cap lower bound to -0.40
replace l90 = -0.4 if l90 < -0.4 
replace l95 = -0.4 if l95 < -0.4 

** cap upper bound to 1.5
replace u90 = 1.5 if u90 > 1.5
replace u95 = 1.5 if u95 > 1.5

	* gen indicators and scatters
	local scoff=" "
	local scon=" "
	local ind=`INITIAL'
	
	local ind=`ind'-`JUMP2'
	foreach var in CONTROLS   {
	   cap gen i_`var'=`ind'
	   local ind=`ind'-`JUMP'
	   local scoff="`scoff' (scatter i_`var' rank,msize(vsmall) mcolor(gs10))" 
	   local scon="`scon' (scatter i_`var' rank if `var'==1,msize(vsmall) mcolor(black))" 
	}
	* samples - distances
	local ind=`ind'-`JUMP2'
	foreach i in 200 350 500 {
	cap gen i_dist`i'=`ind'
	local ind=`ind'-`JUMP'
	   local scoff="`scoff' (scatter i_dist`i' rank,msize(vsmall) mcolor(gs10))" 
	   local scon="`scon' (scatter i_dist`i' rank if dist`i'==1,msize(vsmall) mcolor(black))" 
	}
	* samples - year window
	local ind=`ind'-`JUMP2'
	foreach i in 3 2 1 {
		cap gen i_year`i'=`ind'
		local ind=`ind'-`JUMP'
	   local scoff="`scoff' (scatter i_year`i' rank,msize(vsmall) mcolor(gs10))" 
	   local scon="`scon' (scatter i_year`i' rank if year`i'==1,msize(vsmall) mcolor(black))" 
	}
	* samples - donut
	local ind=`ind'-`JUMP2'
	foreach i in BASELINE RING HOLE {
		cap gen i_`i'=`ind'
		local ind=`ind'-`JUMP'
	   local scoff="`scoff' (scatter i_`i' rank,msize(vsmall) mcolor(gs10))" 
	   local scon="`scon' (scatter i_`i' rank if `i'==1,msize(vsmall) mcolor(black))" 
	}
	* samples - residence requirement
	local ind=`ind'-`JUMP2'
	foreach i in 5 10 15 {
		cap gen i_tenure`i'=`ind'
		local ind=`ind'-`JUMP'
	   local scoff="`scoff' (scatter i_tenure`i' rank,msize(vsmall) mcolor(gs10))" 
	   local scon="`scon' (scatter i_tenure`i' rank if tenure`i'==1,msize(vsmall) mcolor(black))" 
	}

grstyle init
grstyle set legend 10, inside

local COL blue

* plot
tw  (scatter beta rank if main==1, mcolor(`COL') msymbol(D)  msize(vsmall) ) ///  main spec 
   (rbar u95 l95 rank , fcolor(gs12) lcolor(gs12) lwidth(none)) /// 95% CI
   (rbar u90 l90 rank , fcolor(gs6) lcolor(gs16) lwidth(none)) /// 90% CI
   (scatter beta rank , mcolor(black) msymbol(D) msize(vsmall)) ///  point estimates
   `scoff' `scon' /// indicators for spec
  (scatter beta rank if main==1, mcolor(`COL') msymbol(D)  msize(vsmall)) ///  main spec 
  (scatter i_dist350 rank if main==1,msize(vsmall) mcolor(`COL'))  ///
  (scatter i_CONTROLS rank if main==1,msize(vsmall) mcolor(`COL'))  ///
  (scatter i_tenure5 rank if main==1,msize(vsmall) mcolor(`COL'))  ///
  (scatter i_year3 rank if main==1,msize(vsmall) mcolor(`COL'))  ///
  (scatter i_BASELINE rank if main==1,msize(vsmall) mcolor(`COL'))  ///
   ,legend (order(1 "Baseline" 4 "Point estimate" 2 "95% CI" 3 "90% CI") region(lcolor(white)) ///
	ring(1) rows(2) size(vsmall) symysize(small) symxsize(small)) /// 
   xtitle(" ") ytitle(" ") ///
   title("`tit'", size(vsmall) col(black)) ///
   yscale(noline) xscale(noline) ylab(`SCALE',noticks nogrid angle(horizontal) labsize(vsmall)) xlab("", noticks) ///
   graphregion (fcolor(white) lcolor(white)) plotregion(fcolor(white) lcolor(white))
  
local msize tiny

* move legend
gr_edit .legend.DragBy -1.5 1.5
  
* controls 
gr_edit .yaxis1.add_ticks `l1' `"Controls"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )

* trear dist
gr_edit .yaxis1.add_ticks `l3' `"Bldng within 200m"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l4' `"Bldng within 350m"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l5' `"Bldng within 500m"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )

* year-window
gr_edit .yaxis1.add_ticks `l7' `"Treatment in 2017-19"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l8' `"Treatment in 2018-19"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l9' `"Treatment in 2019"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )

* identification
gr_edit .yaxis1.add_ticks `l11' `"Baseline Id"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l12' `"Ring Id"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l13' `"Double Ring Id"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )

* years in prop
gr_edit .yaxis1.add_ticks `l15' `"5+ Years in Prop"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l16' `"10+ Years in Prop"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )
gr_edit .yaxis1.add_ticks `l17' `"15+ Years in Prop"', custom tickset(major) editstyle(tickstyle(textstyle(size(`msize'))) )

* add line
local lowx 0.5
local lowy -0.4
local highx 100.5
local highy 1.50

gr_edit  .plotregion1.AddLine added_lines editor 24.25 `lowy' 24.25 1.20
gr_edit .plotregion1.added_lines_new = 1
gr_edit .plotregion1.added_lines_rec = 1
gr_edit .plotregion1.added_lines[1].style.editstyle  linestyle( width(thin) color(black) pattern(solid)) headstyle( symbol(circle) linestyle( width(thin) color(black) pattern(solid)) fillcolor(black) size(medium) angle(stdarrow) backsymbol(none) backline( width(thin) color(black) pattern(solid)) backcolor(black) backsize(zero) backangle(stdarrow)) headpos(neither) editcopy
gr_edit .plotregion1.added_lines[1].style.editstyle linestyle(width(vthin)) editcopy
gr_edit .plotregion1.added_lines[1].style.editstyle linestyle(pattern(dash)) editcopy   

* second line
if "`outcome'"=="PercGini" {
	gr_edit  .plotregion1.AddLine added_lines editor 74.5 `lowy' 74.5 `highy'
}
else if "`outcome'"=="PrefRedScaled" {
	gr_edit  .plotregion1.AddLine added_lines editor 75.5 `lowy' 75.5 `highy'
}

gr_edit .plotregion1.added_lines_new = 2
gr_edit .plotregion1.added_lines_rec = 2
gr_edit .plotregion1.added_lines[2].style.editstyle  linestyle( width(thin) color(black) pattern(solid)) headstyle( symbol(circle) linestyle( width(thin) color(black) pattern(solid)) fillcolor(black) size(medium) angle(stdarrow) backsymbol(none) backline( width(thin) color(black) pattern(solid)) backcolor(black) backsize(zero) backangle(stdarrow)) headpos(neither) editcopy
gr_edit .plotregion1.added_lines[2].style.editstyle linestyle(width(vthin)) editcopy
gr_edit .plotregion1.added_lines[2].style.editstyle linestyle(pattern(dash)) editcopy   

local ycol red
gr_edit  .plotregion1.AddLine added_lines editor `lowx' 0 `highx' 0
gr_edit .plotregion1.added_lines_new = 3
gr_edit .plotregion1.added_lines_rec = 3
gr_edit .plotregion1.added_lines[3].style.editstyle  linestyle( width(thin) color(`ycol') pattern(solid)) headstyle( symbol(circle) linestyle( width(thin) color(`ycol') pattern(solid)) fillcolor(`ycol') size(medium) angle(stdarrow) backsymbol(none) backline( width(thin) color(`ycol') pattern(solid)) backcolor(`ycol') backsize(zero) backangle(stdarrow)) headpos(neither) editcopy
gr_edit .plotregion1.added_lines[3].style.editstyle linestyle(width(vthin)) editcopy
gr_edit .plotregion1.added_lines[3].style.editstyle linestyle(pattern(dash)) editcopy   

* box
gr_edit  .plotregion1.AddLine added_lines editor `lowx' `lowy' `highx' `lowy'
gr_edit  .plotregion1.AddLine added_lines editor `lowx' `highy' `highx' `highy'
gr_edit  .plotregion1.AddLine added_lines editor `lowx' `lowy' `lowx' `highy'
gr_edit  .plotregion1.AddLine added_lines editor `highx' `lowy' `highx' `highy'

* store
graph export "$figs/SpecCurve_`outcome'_rev.pdf", replace

} 
}
********************************************************************************
* closing
********************************************************************************
{
	
* erase temp file
cap erase "$data/temp/survanalysis_check_qe.dta"

cap log close
clear all

}
